如何组合多个字典,将Python中的公共键的值相加(并保留值为0的值)?
How to combine multiple dicts, summing the values of common keys (and retaining those with value 0) in Python?
给定三个字典 d1、d2 和 d3:
d1
{'a':1,'b':2,'c':3, 'd':0)
d2
{'b':76}
d3
{'a': 45, 'c':0}
有些键名对于多个字典是通用的(实际上,它们将代表同一个现实生活中的对象)。其他如d1中的'd'只存在于d2中。我想将所有字典组合在一起,首先对公共键的值求和, 最终得到:
{'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 almost 有效,但如果键 d 的值为零,则结果计数器中缺少键 d,这是以上。
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})
未测试:
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)
如果您希望 0 键持续存在,您可以使用 update
而不是 +
和 Counter
:
>>> c = Counter()
>>> for d in d1, d2, d3:
... c.update(d)
...
>>> c
Counter({'b': 78, 'a': 46, 'c': 3, 'd': 0})
(这可能是一个复制品,但我现在找不到它。)
collections.defaultdict
救援
import collections
d = collections.defaultdict(int)
for thing in [d1, d2, d3]:
for k, v in thing.items():
d[k] += v
给定三个字典 d1、d2 和 d3:
d1
{'a':1,'b':2,'c':3, 'd':0)
d2
{'b':76}
d3
{'a': 45, 'c':0}
有些键名对于多个字典是通用的(实际上,它们将代表同一个现实生活中的对象)。其他如d1中的'd'只存在于d2中。我想将所有字典组合在一起,首先对公共键的值求和, 最终得到:
{'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 almost 有效,但如果键 d 的值为零,则结果计数器中缺少键 d,这是以上。
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})
未测试:
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)
如果您希望 0 键持续存在,您可以使用 update
而不是 +
和 Counter
:
>>> c = Counter()
>>> for d in d1, d2, d3:
... c.update(d)
...
>>> c
Counter({'b': 78, 'a': 46, 'c': 3, 'd': 0})
(这可能是一个复制品,但我现在找不到它。)
collections.defaultdict
救援
import collections
d = collections.defaultdict(int)
for thing in [d1, d2, d3]:
for k, v in thing.items():
d[k] += v