如何在字典中一起添加值



我有两个来自JSON API的字典,它们在字典中包含另一个字典。它看起来像这样:

dict1 = {"abc": 0, "efg": {"123": 10, "456": 5}}
dict2 = {"abc": 10, "efg": {"123": 7, "456": 3}}

我想把两个字典中的值加在一起,结果看起来像这样

result = {"abc": 10, "efg": {"123": 17, "456": 8}}

我怎样才能得到结果?我已经试过了。计数器,但有一个限制,只能对正整数工作,我尝试使用以下代码

result = {key: dict1.get(key, 0) + dict2.get(key, 0)
for key in set(dict1) | set(dict2)}

但这只适用于普通int而不是dictionary中的dictionary

您可以像这样在递归函数中添加它们:

dict1 = {"abc": 0, "efg": {"123": 10, "456": 5}}
dict2 = {"abc": 10, "efg": {"123": 7, "456": 3}}
def add(dict1,dict2):
for key in dict2: 
if key in dict1:
if not isinstance(dict1[key],dict):
dict2[key] = dict2[key] + dict1[key]
else:
add(dict1[key],dict2[key])
add(dict1,dict2)
print(dict2) 

输出:

{'abc': 10, 'efg': {'123': 17, '456': 8}}

我以前就遇到过这个问题。结果比预期的要复杂一些,特别是当您需要处理没有相同键的嵌套字典时。

这是我当时写的函数。这不是最易读的代码,但它对我来说工作得很好。

def merge_dict(dictA, dictB):
"""(dict, dict) => dict
Merge two dicts, if they contain the same keys, it sums their values.
Return the merged dict.

Example:
dictA = {'any key':1, 'point':{'x':2, 'y':3}, 'something':'aaaa'}
dictB = {'any key':1, 'point':{'x':2, 'y':3, 'z':0, 'even more nested':{'w':99}}, 'extra':8}
merge_dict(dictA, dictB)

{'any key': 2,
'point': {'x': 4, 'y': 6, 'z': 0, 'even more nested': {'w': 99}},
'something': 'aaaa',
'extra': 8}
"""
r = {}
common_k = [k for k in dictA if k in dictB]
for k, v in dictA.items():
# add unique k of dictA
if k not in common_k:
r[k] = v
else:
# add inner keys if they are not containing other dicts
if type(v) is not dict:
if k in dictB:
r[k] = v + dictB[k]
else:
# recursively merge the inner dicts
r[k] = merge_dict(dictA[k], dictB[k])
# add unique k of dictB
for k, v in dictB.items():
if k not in common_k:
r[k] = v
return r

相关内容

  • 没有找到相关文章

最新更新