1

See the problem described here. I want to use collections.Counter, but any key whose sum-of-value amounts to 0 - in this case d1 - gets omitted:

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?

Community
  • 1
  • 1
Pyderman
  • 14,809
  • 13
  • 61
  • 106
  • In counter the value off missing element is `0`. So, if you do `c = Counter({'b': 78, 'a': 46, 'c': 3})`. c['d'] will be 0 but so will be any key other than 'a', 'b', 'c' – sagarchalise Jul 05 '15 at 01:42

0 Answers0