使用给定列表更新深度嵌套的字典
Update a deeply nested dictionary with a given list
我使用 Python 3.9,我有一个问题,我有一个列表:
keyList = ['a', 'b', 'c', 'd']
我也有一本字典,我想按以下方式编辑(更新)这本字典:
myDict = {}
#some code to add the keyList to myDict, this is my question, because I don't know...
myDict = {'a' : {'b' : {'c' : {'d' : 1}}}}
#or when myDict isn't equal to {}
myDict = {'a' : {'c' : 1}}
#same code to add the keyList to myDict
myDict = {'a' : {'c' : 1, 'b' : {'c' : {'d' : 1}}}}
#same code to add the keyList to myDict, but when it is created, add the +1 to value:
myDict = {'a' : {'c' : 1, 'b' : {'c' : {'d' : 2}}}}
IIUC,你可以迭代使用dict.setdefault
:
def update_myDict(myDict):
d = myDict
for k in keyList:
if k == keyList[-1]:
d[k] = d.get(k, 0) + 1
else:
d = d.setdefault(k, {})
return myDict
输出:
>>> update_myDict({})
{'a': {'b': {'c': {'d': 1}}}}
>>> update_myDict({'a' : {'c' : 1}})
{'a': {'c': 1, 'b': {'c': {'d': 1}}}}
>>> update_myDict({'a' : {'c' : 1, 'b' : {'c' : {'d' : 1}}}})
{'a': {'c': 1, 'b': {'c': {'d': 2}}}}
我使用 Python 3.9,我有一个问题,我有一个列表:
keyList = ['a', 'b', 'c', 'd']
我也有一本字典,我想按以下方式编辑(更新)这本字典:
myDict = {}
#some code to add the keyList to myDict, this is my question, because I don't know...
myDict = {'a' : {'b' : {'c' : {'d' : 1}}}}
#or when myDict isn't equal to {}
myDict = {'a' : {'c' : 1}}
#same code to add the keyList to myDict
myDict = {'a' : {'c' : 1, 'b' : {'c' : {'d' : 1}}}}
#same code to add the keyList to myDict, but when it is created, add the +1 to value:
myDict = {'a' : {'c' : 1, 'b' : {'c' : {'d' : 2}}}}
IIUC,你可以迭代使用dict.setdefault
:
def update_myDict(myDict):
d = myDict
for k in keyList:
if k == keyList[-1]:
d[k] = d.get(k, 0) + 1
else:
d = d.setdefault(k, {})
return myDict
输出:
>>> update_myDict({})
{'a': {'b': {'c': {'d': 1}}}}
>>> update_myDict({'a' : {'c' : 1}})
{'a': {'c': 1, 'b': {'c': {'d': 1}}}}
>>> update_myDict({'a' : {'c' : 1, 'b' : {'c' : {'d' : 1}}}})
{'a': {'c': 1, 'b': {'c': {'d': 2}}}}