eri*_*ric 13 python dictionary nested python-2.7
我正在尝试更新嵌套字典中的值,而不会在密钥已存在时覆盖以前的条目.例如,我有一本字典:
myDict = {}
myDict["myKey"] = { "nestedDictKey1" : aValue }
Run Code Online (Sandbox Code Playgroud)
给予,
print myDict
>> { "myKey" : { "nestedDictKey1" : aValue }}
Run Code Online (Sandbox Code Playgroud)
现在,我想在下面添加另一个条目 "myKey"
myDict["myKey"] = { "nestedDictKey2" : anotherValue }}
Run Code Online (Sandbox Code Playgroud)
这将返回:
print myDict
>> { "myKey" : { "nestedDictKey2" : anotherValue }}
Run Code Online (Sandbox Code Playgroud)
但我想要:
print myDict
>> { "myKey" : { "nestedDictKey1" : aValue ,
"nestedDictKey2" : anotherValue }}
Run Code Online (Sandbox Code Playgroud)
有没有办法更新或附加"myKey"新值,而不会覆盖以前的值?
All*_*uce 13
这是处理嵌套dicts的一个非常好的通用解决方案:
import collections
def makehash():
return collections.defaultdict(makehash)
Run Code Online (Sandbox Code Playgroud)
这允许嵌套键设置在任何级别:
myDict = makehash()
myDict["myKey"]["nestedDictKey1"] = aValue
myDict["myKey"]["nestedDictKey2"] = anotherValue
myDict["myKey"]["nestedDictKey3"]["furtherNestedDictKey"] = aThirdValue
Run Code Online (Sandbox Code Playgroud)
对于单级嵌套,defaultdict可以直接使用:
from collections import defaultdict
myDict = defaultdict(dict)
myDict["myKey"]["nestedDictKey1"] = aValue
myDict["myKey"]["nestedDictKey2"] = anotherValue
Run Code Online (Sandbox Code Playgroud)
这是一种仅使用的方式dict:
try:
myDict["myKey"]["nestedDictKey2"] = anotherValue
except KeyError:
myDict["myKey"] = {"nestedDictKey2": anotherValue}
Run Code Online (Sandbox Code Playgroud)
您可以使用collections.defaultdict它,只需在嵌套字典中设置键值对.
from collections import defaultdict
my_dict = defaultdict(dict)
my_dict['myKey']['nestedDictKey1'] = a_value
my_dict['myKey']['nestedDictKey2'] = another_value
Run Code Online (Sandbox Code Playgroud)
或者,您也可以将最后两行写为
my_dict['myKey'].update({"nestedDictKey1" : a_value })
my_dict['myKey'].update({"nestedDictKey2" : another_value })
Run Code Online (Sandbox Code Playgroud)