I have a list of dictionaries that I would like to combine into one dictionary and add the values from each dictionary in the list. For example:
ds = [{1: 1, 2: 0, 3: 0}, {1: 2, 2: 1, 3: 0}, {1: 3, 2: 2, 3: 1, 4: 5}]
The final results should be a single dictionary:
merged = {1: 6, 2: 3, 3: 1, 4: 5}
I'm interested in performance and am looking for the fastest implementation that can merge a list of n-dictionaries into one dictionary and sum the values. An obvious implementation is:
from collections import defaultdict
merged = defaultdict(int)
for d in ds:
for k, v in d.items():
merged[k] += v
Is there a faster way to do this in Python 2.6?