如何组合多个分数,在Python中求和公共密钥的值(并保留值为0)的值? [英] How to combine multiple dicts, summing the values of common keys (and retaining those with value 0) in Python?
问题描述
d1
{'a':1,'b':2,'c':3,'d':0)
d2
{'b' 76}
d3
{'a':45,'c':0}
有一些关键名称是多个dict的共同(实际上,它们将代表相同的现实生活对象)。其他如d1中的'd'只存在于d2中。我想将所有的分组合在一起,首先总结公共密钥的值,结束于:
{'a':46,'b':78,'c':3,'d':0}
如果每个dict的大小相同,并且包含相同的密钥,我可以执行以下操作:
summedAndCombined = {}
for k,v in d1.items():
summedAndCombined [k] = d1 [k] + d2 [k] + d3 [k]
但是,一旦达到d1中的键但不在其他键中,这将分解。我们如何实现这一目标?
更新
不重复。 Collections.Counter 几乎可以正常工作,但如果key d的值为0,则该结果计数器中缺少密钥 d 。
在[128]中:d1 = {'a':1,'b':2,'c':3,'d ':0}
在[129]中:d2 = {'b':76}
在[130]中:d3 = {'a':45,'c ':0}
在[131]中:从集合导入计数器
在[132]中:计数器(d1)+计数器(d2)+计数器(d3)
出[132]:Counter({'b':78,'a':46,'c':3})
您可以使用更新
而不是 +
与计数器
如果你想要保持0键:
> ;>> c = Counter()
>>>对于d中的d,d2,d3:
... c.update(d)
...
>>> c
计数器({'b':78,'a':46,'c':3,'d':0})
(这可能是一个dup,但我现在找不到)。
Given three dicts d1, d2 and d3:
d1
{'a':1,'b':2,'c':3, 'd':0)
d2
{'b':76}
d3
{'a': 45, 'c':0}
There are some key names that are common to more than one dict (and in reality, they will represent the same real-life object). Others such as 'd' in d1 only exist in d2. I want to group all dicts together, first summing the values of the common keys first, ending up with:
{'a':46, 'b':78, 'c':3, 'd': 0}
If every dict were the same size and contained the same keys, I could do something like:
summedAndCombined = {}
for k,v in d1.items():
summedAndCombined[k] = d1[k]+d2[k]+d3[k]
But this will break down as soon as it reaches a key that is in d1 but not in the others. How do we achieve this?
UPDATE
Not a duplicate. collections.Counter almost works, but the key d is missing from the resulting Counter if the value of key d is zero, which it is above.
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})
You could use update
instead of +
with Counter
if you want the 0 keys to persist:
>>> c = Counter()
>>> for d in d1, d2, d3:
... c.update(d)
...
>>> c
Counter({'b': 78, 'a': 46, 'c': 3, 'd': 0})
(This is probably a dup, but I can't find it right now.)
这篇关于如何组合多个分数,在Python中求和公共密钥的值(并保留值为0)的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!