Merging multiple dictionaries conditionally

I have N dictionaries containing the same keys with values ​​that are integers. I want to combine them into one dictionary based on the maximum value. I currently have something like this:

max_dict = {} for dict in original_dict_list: for key, val in dict.iteritems(): if key not in max_dict or max_dict[key] < val: max_dict[key] = val 

Is there a better (or more "pythonic") way to do this?

+7
python dictionary
source share
3 answers

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}) 
+7
source share

Assuming that not all dictionaries contain all keys:

 keys = set(k for x in original_dict_list for k in x) max_dict = {k:max([x[k] for x in original_dict_list if k in x]) for k in keys} 
+2
source share
 max_dict = { k:max([v]+[ _dict[k] for _dict in original_dict_list[1:] ]) for k,v in original_dict_list[0].items() } 
0
source share

All Articles