Get maximum keys from a dictionary list

If I have:

dicts = [{'a': 4,'b': 7,'c': 9}, {'a': 2,'b': 1,'c': 10}, {'a': 11,'b': 3,'c': 2}] 

How to get the maximum keys, for example:

 {'a': 11,'c': 10,'b': 7} 
+4
source share
4 answers

Use collection.Counter() objects instead or convert dictionaries:

 from collections import Counter result = Counter() for d in dicts: result |= Counter(d) 

or even:

 from collections import Counter from operator import or_ result = reduce(or_, map(Counter, dicts), Counter()) 

Counter objects support the search for the maximum value for each key due to operation | ; & gives you a minimum.

Demo:

 >>> result = Counter() >>> for d in dicts: ... result |= Counter(d) ... >>> result Counter({'a': 11, 'c': 10, 'b': 7}) 

or using the reduce() version:

 >>> reduce(or_, map(Counter, dicts), Counter()) Counter({'a': 11, 'c': 10, 'b': 7}) 
+8
source
 >>> dicts = [{'a': 4,'b': 7,'c': 9}, ... {'a': 2,'b': 1,'c': 10}, ... {'a': 11,'b': 3,'c': 2}] >>> {letter: max(d[letter] for d in dicts) for letter in dicts[0]} {'a': 11, 'c': 10, 'b': 7} 
+4
source
 dicts = [{'a': 4,'b': 7,'c': 9}, {'a': 2,'b': 1,'c': 10}, {'a': 11,'b': 3,'c': 2}] def get_max(dicts): res = {} for d in dicts: for k in d: res[k] = max(res.get(k, float('-inf')), d[k]) return res >>> get_max(dicts) {'a': 11, 'c': 10, 'b': 7} 
+1
source

Something like this should work:

 dicts = [{'a': 4,'b': 7,'c': 9}, {'a': 2,'b': 1,'c': 10}, {'a': 11,'b': 3,'c': 2}] max_keys= {} for d in dicts: for k, v in d.items(): max_keys.setdefault(k, []).append(v) for k in max_keys: max_keys[k] = max(max_keys[k]) 
0
source

Source: https://habr.com/ru/post/1486438/


All Articles