【问题标题】:How to combine multiple dicts, summing the values of common keys (and retaining those with value 0) in Python? [duplicate]如何在 Python 中组合多个 dicts,对公共键的值求和(并保留值为 0 的键)? [复制]
【发布时间】:2015-09-22 10:49:01
【问题描述】:

给定三个字典 d1、d2 和 d3:

d1

{'a':1,'b':2,'c':3, 'd':0)

d2

{'b':76}

d3

{'a': 45, 'c':0}

有一些键名对多个 dict 是通用的(实际上,它们将代表同一个现实生活中的对象)。其他如 d1 中的 'd' 仅存在于 d2 中。我想将所有 dicts 组合在一起,首先将公共键的值相加,最终得到:

{'a':46, 'b':78, 'c':3, 'd': 0}

如果每个字典的大小相同并且包含相同的键,我可以这样做:

summedAndCombined = {}
    for k,v in d1.items():
        summedAndCombined[k] = d1[k]+d2[k]+d3[k]

但是,一旦它到达 d1 中但不在其他中的键,它就会崩溃。我们如何实现这一目标?

更新

不是重复的。 collections.Counter 几乎可以工作,但是如果键 d 的值为零,则结果 Counter 中缺少键 d p>

In [128]: d1 = {'a':1,'b':2,'c':3, 'd':0}

In [129]: d2 = {'b':76}

In [130]: d3 = {'a': 45, 'c':0}

In [131]: from collections import Counter

In [132]: Counter(d1) + Counter(d2) + Counter(d3)
Out[132]: Counter({'b': 78, 'a': 46, 'c': 3})

【问题讨论】:

  • if k in d2.keys() ...

标签: python python-2.7 dictionary iteration defaultdict


【解决方案1】:

如果您希望 0 键保持不变,您可以使用 update 而不是 +Counter

>>> c = Counter()
>>> for d in d1, d2, d3:
...     c.update(d)
...     
>>> c
Counter({'b': 78, 'a': 46, 'c': 3, 'd': 0})

(这可能是一个副本,但我现在找不到。)

【讨论】:

    【解决方案2】:

    collections.defaultdict 救援

    import collections
    d = collections.defaultdict(int)
    for thing in [d1, d2, d3]:
        for k, v in thing.items():
            d[k] += v
    

    【讨论】:

      【解决方案3】:

      未经测试:

      def merge_dicts(*dicts):
          res = {}
          for key in set(sum(map(list, dicts), [])):
              res[key] = 0
              for dct in dicts:
                  res[key] += dct.get(key, 0)
          return res
      

      示例用法:

      merge_dicts(d1, d2, d3)
      

      【讨论】:

        猜你喜欢
        • 2020-08-05
        • 2023-03-28
        • 2019-10-14
        • 1970-01-01
        • 2011-01-05
        • 2017-04-24
        • 1970-01-01
        • 2014-09-04
        • 1970-01-01
        相关资源
        最近更新 更多