这是很早之前百度到的国外的代码,我是菜鸟,我感觉这段代码很强悍。分享给大家。
def setdict(d, attrs=[]):
# Adds "val" to dict in the hierarchy mentioned via *attrs
for attr in attrs[:-2]:
# If such key is not found or the value is primitive supply an empty dict
if d.get(attr) is None: ##or isinstance(d.get(attr), dict):
d[attr] = {}
d = d[attr]
d[attrs[-2]] = attrs[-1]
通过打印过程中id(d)的变化,才搞清咋回事。我私自改了一下。
def xsetdict(d, attrs=[]):
for attr in attrs[:-2]:
if d.get(attr) is None: ##or isinstance(d.get(attr), dict):
print(id(d),' ->', d)
d[attr] = {}
print(id(d), ' -->', d)
d = d[attr]
print(id(d), ' --->', d)
d[attrs[-2]] = [attrs[-1]] + d.get(attrs[-2],[])
xx = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘x’]
res = {}
setdict(res,xx)
print(res)
#结果:
{‘a’: {‘b’: {‘c’: {‘d’: {‘e’: [‘x’]}}}}}



