I have several dictionaries which I'd like to combine such that if a key is in multiple dictionaries the values are added together. For example:
d1 = {1: 10, 2: 20, 3: 30}
d2 = {1: 1, 2: 2, 3: 3}
d3 = {0: 0}
merged = {1: 11, 2: 22, 3: 33, 0: 0}
What is the best way to do this in Python? I was looking at defaultdict and trying to come up with something. I'm using Python 2.6.
using a defaultdict
:
>>> d = defaultdict(int)
>>> for di in [d1,d2,d3]:
... for k,v in di.items():
... d[k] += v
...
>>> dict(d)
{0: 0, 1: 11, 2: 22, 3: 33}
>>>
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