You can use collections.Counter()
(only works for positive values!):
In [17]: from collections import Counter In [18]: sum((Counter(d) for d in data.values()), Counter()) Out[18]: Counter({'C': 12, 'B': 7, 'A': 4, 'D': 3})
Note that based on the documentation, python Counter
is only for cases with positive values:
Multi-user methods are for use only with positive values. Inputs can be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type must support addition, subtraction, and comparison. The elements()
method requires integer calculations. It ignores null and negative values.
So, if you want to get a comprehensive result, you can perform the summation manually. collections.defaultdict()
is a good way around this problem:
In [28]: from collections import defaultdict In [29]: d = defaultdict(int) In [30]: for sub in data.values(): ....: for i, j in sub.items(): ....: d[i] += j ....: In [31]: d Out[31]: defaultdict(<class 'int'>, {'D': -15, 'A': 4, 'C': 12, 'B': 7})
source share