gpt4 book ai didi

python - 合并两个字典的字典(Python)

转载 作者:太空宇宙 更新时间:2023-11-03 13:05:00 24 4
gpt4 key购买 nike

有没有一种简单的方法可以在 Python 中组合两个字典的字典?这是我需要的:

dict1 = {'A' : {'B' : 'C'}}
dict2 = {'A' : {'D' : 'E'}}

result = dict_union(dict1, dict2)
# => result = {'A' : {'B' : 'C', 'D' : 'E'}}

我创建了一个强力函数来执行此操作,但我一直在寻找更紧凑的解决方案:

def dict_union(train, wagon):
for key, val in wagon.iteritems():
if not isinstance(val, dict):
train[key] = val
else:
subdict = train.setdefault(key, {})
dict_union(subdict, val)

最佳答案

这是一个类 RUDict(用于递归更新字典),它实现了您正在寻找的行为:

class RUDict(dict):

def __init__(self, *args, **kw):
super(RUDict,self).__init__(*args, **kw)

def update(self, E=None, **F):
if E is not None:
if 'keys' in dir(E) and callable(getattr(E, 'keys')):
for k in E:
if k in self: # existing ...must recurse into both sides
self.r_update(k, E)
else: # doesn't currently exist, just update
self[k] = E[k]
else:
for (k, v) in E:
self.r_update(k, {k:v})

for k in F:
self.r_update(k, {k:F[k]})

def r_update(self, key, other_dict):
if isinstance(self[key], dict) and isinstance(other_dict[key], dict):
od = RUDict(self[key])
nd = other_dict[key]
od.update(nd)
self[key] = od
else:
self[key] = other_dict[key]


def test():
dict1 = {'A' : {'B' : 'C'}}
dict2 = {'A' : {'D' : 'E'}}

dx = RUDict(dict1)
dx.update(dict2)
print(dx)


if __name__ == '__main__':
test()


>>> import RUDict
>>> RUDict.test()
{'A': {'B': 'C', 'D': 'E'}}
>>>

关于python - 合并两个字典的字典(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6256183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com