首页 > 解决方案 > 如何将字典中的值相加

问题描述

我有两个来自 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 而不是字典中的字典

标签: pythonpython-3.xalgorithmdictionarymerge

解决方案


我过去有这个问题。结果比预期的要复杂一些,特别是如果您需要处理没有所有相同键的嵌套字典。

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

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

推荐阅读