python - 如何将字典中的值相加
问题描述
我有两个来自 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}}
我怎样才能得到结果?我已经尝试过 collections.Counter 但它的限制只能用于正 int ,我尝试使用以下代码
result = {key: dict1.get(key, 0) + dict2.get(key, 0)
for key in set(dict1) | set(dict2)}
但这仅适用于普通 int 而不是字典中的字典
解决方案
我过去有这个问题。结果比预期的要复杂一些,特别是如果您需要处理没有所有相同键的嵌套字典。
这是我当时写的函数。它不是最易读的代码,但对我来说效果很好。
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
推荐阅读
- r - 有什么方法可以在 gganimate 中使用 transition_reveal 在特定帧/时间点暂停?
- python - Python2.7 Dict 元素的更改和访问值
- typescript - Angular 6 Router - 子路由不起作用
- amazon-s3 - Spring Cloud:使用 TestContainers 测试 S3 客户端
- javascript - JS,CSS)从字符串中获取字母并使每个字母顺利落下(NO JQUERY
- javascript - 每秒调用一次函数 max
- verilog - 在 Verilog 中声明向量端口而不指定它们的大小
- java - JPanel 位置被 BufferStrategy 重击
- c# - 基于内部属性展平集合
- java - 尝试为数字创建验证,尝试测试时崩溃