python分数求和,如何组合多个分数,在Python中求和公共密钥的值(并保留值为0)的值?...

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.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值