Sum values ​​of similar keys inside two nested dictionaries in python

I have a nested dictionary:

data = { "2010":{ 'A':2, 'B':3, 'C':5, 'D':-18, }, "2011":{ 'A':1, 'B':2, 'C':3, 'D':1, }, "2012":{ 'A':1, 'B':2, 'C':4, 'D':2 } } 

In my case, I need to sum all the values ​​based on its similar keys every year, from 2010 to 2012. Therefore, the expected result should look like this:

 data = {'A':4,'B':7, 'C':12, 'D':-15} 
+6
source share
2 answers

Try it,

 reduce(lambda x, y: dict((k, v + y[k]) for k, v in x.iteritems()), data.values()) 

Result

 {'A': 4, 'B': 7, 'C': 12, 'D': -15} 
+1
source

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}) 
+4
source

Source: https://habr.com/ru/post/1015611/


All Articles