【问题标题】:How to add values in dictionaries together如何将字典中的值相加
【发布时间】:2021-05-13 09:41:03
【问题描述】:

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

【问题讨论】:

  • 请就您遇到的特定错误提出特定问题。这个网站不是为了简单地提供代码。

标签: python python-3.x algorithm dictionary merge


【解决方案1】:

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

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}}

【讨论】:

    【解决方案2】:

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

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-19
      • 2021-12-30
      • 2022-11-14
      • 2021-05-17
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多