Inspired from this question
I have an arbitrary number of dictionaries (coming from a generator)
a = {"a": 1, "b": 2, "c": 3}
b = {"c": 1, "d": 1}
c = {"a": 2, "b": 2}
...
I want to have a final dictionary that contains the following values for each key:
- If the key appears only in one dictionary, keep this value
- If the key appears in multiple dictionaries, the final value is the sum of the values in the individual dicts.
In my example, the result would be {"a": 3, "b": 4, "c": 4, "d": 1}
Based on the answer of the question linked above, I can use collections.Counter
when having a set number of dictionaries, like this:
from collections import Counter
dict(Counter(a) + Counter(b) + Counter(c))
However, the number of dictionaries I have can be very large, is there any smart one-liner (or close) I can use to get this "sum" I am interested in ?
Sadly, using sum(Counter(d) for d in (a,b,c))
raises a TypeError: unsupported operand type(s) for +: 'int' and 'Counter'