如何停止集合。如果值为0,则忽略一个键?

时间:2015-07-05 01:32:13

标签: python python-2.7 dictionary iteration

查看问题here。我想使用collections.Counter,但任何值和为0的键 - 在这种情况下 d1 - 都会被省略:

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

How to combine multiple dicts, summing the values of common keys (and retaining those with value 0) in Python?

0 个答案:

没有答案