对多个python字典的对应元素求和 [英] Sum corresponding elements of multiple python dictionaries
问题描述
我有任意数量的等长python字典,带有匹配的键集,如下所示:
I have an arbitrary number of equal-length python dictionaries with matching sets of keys, like this:
{'a':1, 'b':4, 'c':8, 'd':9}
{'a':2, 'b':3, 'c':2, 'd':7}
{'a':0, 'b':1, 'c':3, 'd':4}
...
如何获得具有相同键集但值等于字典集中相应元素之和的单个字典?换句话说,我想要:
How can I obtain a single dictionary with the same set of keys but with values as the sums of corresponding elements in the dictionary set? In other words, I'd want:
{'a':3, 'b':8, 'c':13, 'd':20}
也许有一个丑陋,复杂的循环结构,但是有某种更好的方法来实现某种列表/字典理解技巧吗?想到它,我真的不确定如何制作一个丑陋的循环版本..
Maybe there's an ugly, complicated loop structure, but is there a nicer way to do this with some kind of list/dict comprehension cleverness? Come to think of it, I'm really not sure how to make an ugly loop version, anyway..
推荐答案
collections.Counter()
进行救援;-)
from collections import Counter
dicts = [{'a':1, 'b':4, 'c':8, 'd':9},
{'a':2, 'b':3, 'c':2, 'd':7},
{'a':0, 'b':1, 'c':3, 'd':4}]
c = Counter()
for d in dicts:
c.update(d)
然后:
>>> print c
Counter({'d': 20, 'c': 13, 'b': 8, 'a': 3})
或者您可以将其更改回字典:
Or you can change it back to a dict:
>>> print dict(c)
{'a': 3, 'c': 13, 'b': 8, 'd': 20}
Counter()
是否所有输入字典都具有相同的键并不重要.如果您确定知道这样做的话,则可以尝试可笑的;-)这样的单线:
It doesn't matter to Counter()
whether all the input dicts have same keys. If you know for sure that they do, you could try ridiculous ;-) one-liners like this:
d = {k: v for k in dicts[0] for v in [sum(d[k] for d in dicts)]}
Counter()
更清晰,更快,更灵活.公平地说,这种稍微不太荒谬的单行代码也不太荒谬:
Counter()
is clearer, faster, and more flexible. To be fair, though, this slightly less ridiculous one-liner is less ridiculous:
d = {k: sum(d[k] for d in dicts) for k in dicts[0]}
这篇关于对多个python字典的对应元素求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!