Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

summing items in nested dictionary with different keys

I have a nested dictionary along the lines of:

{'apple':  {'a': 1, 'b': 4, 'c': 2},
 'orange': {'a': 4, 'c': 5},
 'pear':   {'a': 1, 'b': 2}}

What I want to do is get rid of the outer keys and sum the values of the inner keys so that I have a new dictionary which looks like:

{'a': 6, 'b': 6, 'c': 7}
like image 976
user1600653 Avatar asked Dec 06 '22 12:12

user1600653


1 Answers

You can use the Counter class:

>>> from collections import Counter

>>> d = {'apple': {'a': 1, 'b': 4, 'c': 2}, 'orange': {'a': 4, 'c': 5}, 'pear': {'a': 1, 'b': 2}}
>>> sum(map(Counter, d.values()), Counter())
Counter({'c': 7, 'a': 6, 'b': 6})
like image 180
sloth Avatar answered Dec 18 '22 16:12

sloth