2014-11-25 36 views
5

我試圖更新嵌套字典中的值,而不會在密鑰已存在時覆蓋以前的條目。 例如,我有一本字典:當數據存在密鑰時更新嵌套字典

myDict = {} 
    myDict["myKey"] = { "nestedDictKey1" : aValue } 

捐贈,

print myDict 
>> { "myKey" : { "nestedDictKey1" : aValue }} 

現在,我想添加其他的記錄,"myKey"

myDict["myKey"] = { "nestedDictKey2" : anotherValue }} 

下,這將返回:

print myDict 
>> { "myKey" : { "nestedDictKey2" : anotherValue }} 

但我想:

print myDict 
>> { "myKey" : { "nestedDictKey1" : aValue , 
       "nestedDictKey2" : anotherValue }} 

有沒有一種方法來更新或追加"myKey"用新值,而不會覆蓋以前的?

回答

5

嘗試是這樣的:

try: 
    myDict["myKey"]["nestedDictKey2"] = anotherValue 
except KeyError: 
    myDict["myKey"] = {"nestedDictKey2": anotherValue} 

該模式會將鍵添加到現有的嵌套詞典或cre如果它不存在,請吃新的嵌套字典。

0
myDict["myKey"]["nestedDictKey2"] = anotherValue 

myDict["myKey"]返回嵌套的詞典,類似的,我們對任何字典:)做,我們可以添加另一個關鍵

例子:

>>> d = {'myKey' : {'k1' : 'v1'}} 
>>> d['myKey']['k2'] = 'v2' 
>>> d 
{'myKey': {'k2': 'v2', 'k1': 'v1'}} 
5

您可以使用collections.defaultdict來實現此目的,只需在嵌套字典中設置鍵值對即可。

from collections import defaultdict 
my_dict = defaultdict(dict) 
my_dict['myKey']['nestedDictKey1'] = a_value 
my_dict['myKey']['nestedDictKey2'] = another_value 

或者,你也可以寫那些最後兩行作爲

my_dict['myKey'].update({"nestedDictKey1" : a_value }) 
my_dict['myKey'].update({"nestedDictKey2" : another_value })