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}
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With