Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get max keys of a list of dictionaries

If I have:

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

How can I get the maximum keys only, like this:

{'a': 11,'c': 10,'b': 7}
like image 809
user2489823 Avatar asked Dec 09 '22 14:12

user2489823


1 Answers

Use collection.Counter() objects instead, or convert your 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 finding the maximum per key natively through the | operation; & gives you the 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})
like image 109
Martijn Pieters Avatar answered Dec 11 '22 10:12

Martijn Pieters