Python 当数据具有现有键时更新嵌套字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27118687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Updating nested dictionaries when data has existing key
提问by eric
I am trying to update values in a nested dictionary, without over-writting previous entries when the key already exists. For example, I have a dictionary:
我正在尝试更新嵌套字典中的值,而不会在键已经存在时覆盖以前的条目。例如,我有一本字典:
myDict = {}
myDict["myKey"] = { "nestedDictKey1" : aValue }
giving,
给予,
print myDict
>> { "myKey" : { "nestedDictKey1" : aValue }}
Now, I want to add another entry , under "myKey"
现在,我想在下面添加另一个条目 "myKey"
myDict["myKey"] = { "nestedDictKey2" : anotherValue }}
This will return:
这将返回:
print myDict
>> { "myKey" : { "nestedDictKey2" : anotherValue }}
But I want:
但我想要:
print myDict
>> { "myKey" : { "nestedDictKey1" : aValue ,
"nestedDictKey2" : anotherValue }}
Is there a way to update or append "myKey"with new values, without overwriting the previous ones?
有没有办法在"myKey"不覆盖以前的值的情况下更新或附加新值?
采纳答案by Allen Luce
This is a very nice general solution to dealing with nested dicts:
import collections
def makehash():
return collections.defaultdict(makehash)
That allows nested keys to be set at any level:
这允许在任何级别设置嵌套键:
myDict = makehash()
myDict["myKey"]["nestedDictKey1"] = aValue
myDict["myKey"]["nestedDictKey2"] = anotherValue
myDict["myKey"]["nestedDictKey3"]["furtherNestedDictKey"] = aThirdValue
For a single level of nesting, defaultdictcan be used directly:
对于单层嵌套,defaultdict可以直接使用:
from collections import defaultdict
myDict = defaultdict(dict)
myDict["myKey"]["nestedDictKey1"] = aValue
myDict["myKey"]["nestedDictKey2"] = anotherValue
And here's a way using only dict:
这是一种仅使用的方法dict:
try:
myDict["myKey"]["nestedDictKey2"] = anotherValue
except KeyError:
myDict["myKey"] = {"nestedDictKey2": anotherValue}
回答by slider
myDict["myKey"]["nestedDictKey2"] = anotherValue
myDict["myKey"]returns the nested dictionary to which we can add another key like we do for any dictionary :)
myDict["myKey"]返回嵌套字典,我们可以像对任何字典一样向其中添加另一个键:)
Example:
例子:
>>> d = {'myKey' : {'k1' : 'v1'}}
>>> d['myKey']['k2'] = 'v2'
>>> d
{'myKey': {'k2': 'v2', 'k1': 'v1'}}
回答by Stuart
You can use collections.defaultdictfor this, and just set the key-value pairs within the nested dictionary.
您可以使用collections.defaultdict它,只需在嵌套字典中设置键值对。
from collections import defaultdict
my_dict = defaultdict(dict)
my_dict['myKey']['nestedDictKey1'] = a_value
my_dict['myKey']['nestedDictKey2'] = another_value
Alternatively, you can also write those last 2 lines as
或者,您也可以将最后两行写为
my_dict['myKey'].update({"nestedDictKey1" : a_value })
my_dict['myKey'].update({"nestedDictKey2" : another_value })
回答by Albert James Teddy
You could treat the nested dict as immutable:
您可以将嵌套的 dict 视为不可变的:
myDict["myKey"] = dict(myDict["myKey"], **{ "nestedDictKey2" : anotherValue })
myDict["myKey"] = dict(myDict["myKey"], **{ "nestedDictKey2" : anotherValue })

