更新嵌套字典中已有键的数据

17

我想更新一个嵌套字典中的值,当键已经存在时不会覆盖先前的条目。 例如,我有一个字典:

  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",而不会覆盖先前的值?
7个回答

19

这是一个非常好的通用解决方案,用于处理嵌套字典:

import collections
def makehash():
    return collections.defaultdict(makehash)

这允许任何层级设置嵌套键:

myDict = makehash()
myDict["myKey"]["nestedDictKey1"] = aValue
myDict["myKey"]["nestedDictKey2"] = anotherValue
myDict["myKey"]["nestedDictKey3"]["furtherNestedDictKey"] = aThirdValue

对于仅有一层嵌套的情况,可以直接使用 defaultdict

from collections import defaultdict
myDict = defaultdict(dict)
myDict["myKey"]["nestedDictKey1"] = aValue
myDict["myKey"]["nestedDictKey2"] = anotherValue

这里有一种只使用dict的方法:

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

10
您可以使用 collections.defaultdict 来实现,并在嵌套字典中设置键值对。
from collections import defaultdict
my_dict = defaultdict(dict)
my_dict['myKey']['nestedDictKey1'] = a_value
my_dict['myKey']['nestedDictKey2'] = another_value

另外,您也可以将最后2行写成以下形式:

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

2
你可以将嵌套的字典视为不可变对象: myDict["myKey"] = dict(myDict["myKey"], **{ "nestedDictKey2" : anotherValue })

1
我认为这是最简洁的解决方案。 - Kots

2
您可以编写一个生成器来更新嵌套字典中的键,就像这样。
def update_key(key, value, dictionary):
        for k, v in dictionary.items():
            if k == key:
                dictionary[key]=value
            elif isinstance(v, dict):
                for result in update_key(key, value, v):
                    yield result
            elif isinstance(v, list):
                for d in v:
                    if isinstance(d, dict):
                        for result in update_key(key, value, d):
                            yield result

list(update_key('Any level key', 'Any value', DICTIONARY))

1
from ndicts.ndicts import NestedDict

nd = NestedDict()
nd["myKey", "nestedDictKey1"] = 0
nd["myKey", "nestedDictKey2"] = 1

>>> nd
NestedDict({'myKey': {'nestedDictKey1': 0, 'nestedDictKey2': 1}})
>>> nd.to_dict()
{'myKey': {'nestedDictKey1': 0, 'nestedDictKey2': 1}}

安装 ndicts 的方法是 pip install ndicts


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

myDict["myKey"] 返回嵌套字典,我们可以像对待任何字典一样添加另一个键 :)

示例:

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

0
我写了一个函数来解决这个问题。
def updateDict2keys(myDict,mykey1,mykey2,myitems):
"""
updates a dictionary by appending values at given keys (generating key2 if not already existing)
input: dictionary, key1, key2 and items to append
output: dictionary orgnanized as {mykey1:{mykey2:myitems}}
"""
    myDict.setdefault(mykey1, {})[mykey2] = myitems
    return myDict

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接