如果我有嵌套字典d = {'a':{'b':{}}}
和字符串'a.b.c'
以及值'X'
我需要根据键字符串将值放在dict中。
我想要实现的内容可以硬编码为d['a']['b']['c'] = 'X'
但我需要动态执行。键串可以是任意长度。
对于奖励积分:我还需要创建密钥,如果它们不存在,如'a.b.z'
,但我相信如果我能解决它们已经存在的情况,我可以弄明白。
答案 0 :(得分:9)
def set(d, key, value):
dd = d
keys = key.split('.')
latest = keys.pop()
for k in keys:
dd = dd.setdefault(k, {})
dd.setdefault(latest, value)
d = {}
set(d, 'a.b.c', 'X')
set(d, 'a.b.d', 'Y')
print(d)
结果:
{'a': {'b': {'c': 'X', 'd': 'Y'}}}
答案 1 :(得分:1)
def recursedict(d,keylist,value=None):
key = keylist.pop(0) # removes and returns the first key
if len(keylist): # True if there are more levels to go down
try: assert type(d[key]) is dict
except KeyError: d[key] = dict()
except AssertionError: raise ValueError("d[{}] is a {}".format(key,type(d[key])))
# if d[key] doesn't exist, make it a dict()
# if d[key] DOES exist, and isn't a dict, raise a KeyError
recursedict(d[key],keylist,value)
# recurse
else:
if value is None:
return d[key]
else:
d[keylist[0]] = value
return value
def setdeepdict(d,attributestr,value): # double entendre intentional
keys = attributestr.split('.')
recursedict(d,keys,value)
def getdeepdict(d,attributestr): # double entendre SUPER intentional
keys = attributestr.split('.')
recursedict(d,keys)