python字典值求和_对多个python字典的对应元素求和

1586010002-jmsa.png

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() to the rescue ;-)

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)

Then:

>>> 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}

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() 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]}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值