Sum of values across all nested dictionaries in python
dictionary, python
Solution
Use a nested comprehension:
sum(x for counter in numbers.values() for x in counter.values())
Or sum first the counters (starting with an empty one), and then their values:
sum(sum(numbers.values(), Counter()).values())
Or first each counter's values, and then the intermediate results:
sum(sum(c.values()) for c in numbers.values())
Or use chain:
from itertools import chain
sum(chain.from_iterable(d.values() for d in numbers.values()))
I prefer the first way.
Problem
I have a dictionary of Counters, e.g: ``` from collections import Counter, defaultdict numbers = defaultdict(Counter) numbers['a']['first'] = 1 numbers['a']['second'] = 2 numbers['b']['first'] = 3 ``` I want to get the sum: 1+2+3 = 6 What would be the simplest / idiomatic way to do this in python 3?