【问题标题】:Add values from two dictionaries从两个字典中添加值
【发布时间】:2018-01-24 14:47:12
【问题描述】:
dict1 = {a: 5, b: 7}
dict2 = {a: 3, c: 1}

result {a:8, b:7, c:1}

我怎样才能得到结果?

【问题讨论】:

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


【解决方案1】:

这是一个可以做到这一点的单线:

dict1 = {'a': 5, 'b': 7}
dict2 = {'a': 3, 'c': 1}

result = {key: dict1.get(key, 0) + dict2.get(key, 0)
          for key in set(dict1) | set(dict2)}
# {'c': 1, 'b': 7, 'a': 8}

请注意,set(dict1) | set(dict2) 是两个字典的键的集合。 dict1.get(key, 0) 如果密钥存在则返回dict1[key],否则返回0


这适用于更新的 python 版本:

{k: dict1.get(k, 0) + dict2.get(k, 0) for k in dict1.keys() | dict2.keys()}

【讨论】:

    【解决方案2】:

    这是一个不错的功能:

    def merge_dictionaries(dict1, dict2):
        merged_dictionary = {}
    
        for key in dict1:
            if key in dict2:
                new_value = dict1[key] + dict2[key]
            else:
                new_value = dict1[key]
    
            merged_dictionary[key] = new_value
    
        for key in dict2:
            if key not in merged_dictionary:
                merged_dictionary[key] = dict2[key]
    
        return merged_dictionary
    

    通过写作:

    dict1 = {'a': 5, 'b': 7}
    dict2 = {'a': 3, 'c': 1}
    result = merge_dictionaries(dict1, dict2)
    

    结果将是:

    {'a': 8, 'b': 7, 'c': 1}
    

    【讨论】:

      【解决方案3】:

      您可以使用 collections.Counter 实现加法 + 的方式:

      >>> from collections import Counter
      >>> dict1 = Counter({'a': 5, 'b': 7})
      >>> dict2 = Counter({'a': 3, 'c': 1})
      >>> dict1 + dict2
      Counter({'a': 8, 'b': 7, 'c': 1})
      

      如果您真的希望结果为 dict,您可以在之后将其转换回:

      >>> dict(dict1 + dict2)
      {'a': 8, 'b': 7, 'c': 1}
      

      【讨论】:

      • 这个实现。有一个问题,它没有计算零值
      • 其实是only keeps positive values,即Counter(a=0, b=1) + Counter(b=-2) == Counter()+这里给了一个空计数器)。
      【解决方案4】:

      一个快速的字典理解,应该适用于任何接受 + 运算符的类。性能可能不是最佳的。

      {
          **dict1,
          **{ k:(dict1[k]+v if k in dict1 else v)
              for k,v in dict2.items() }
      }
      

      【讨论】:

        【解决方案5】:
        Here is another approach but it is quite lengthy!
        
        d1 = {'a': 5, 'b': 7}
        d2 = {'a': 3, 'c': 1}
        
        d={}
        for i,j in d1.items():
            for k,l in d2.items():
                if i==k:
                    c={i:j+l}
                    d.update(c)
        for i,j in d1.items():
            if i not in d:
                d.update({i:j})
        for m,n in d2.items():
            if m not in d:
                d.update({m:n})
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-08
          • 2022-07-10
          • 1970-01-01
          • 2022-07-06
          • 1970-01-01
          相关资源
          最近更新 更多