Use collection.Counter() objects instead, they support "merging" of samples natively:
from collections import Counter max_dict = Counter() for d in original_dict_list: max_dict |= Counter(d)
or even:
from collections import Counter from operator import or_ max_dict = reduce(or_, map(Counter, original_dict_list))
Counter objects are arrays (sometimes called "bags"). Operator | performs combination on two counters, keeping the maximum number for a given key.
A Counter also a direct subclass of dict , so you can (basically) treat it like any other dictionary.
Demo:
>>> from collections import Counter >>> from operator import or_ >>> original_dict_list = [{'foo': 3, 'bar': 10}, {'foo': 42, 'spam': 20}, {'bar': 5, 'ham': 10}] >>> reduce(or_, map(Counter, original_dict_list)) Counter({'foo': 42, 'spam': 20, 'bar': 10, 'ham': 10})
Martijn pieters
source share