user2489823
user2489823

Reputation: 43

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}

Upvotes: 4

Views: 522

Answers (4)

Martijn Pieters
Martijn Pieters

Reputation: 1121396

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})

Upvotes: 8

orlenko
orlenko

Reputation: 1271

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])

Upvotes: 0

Jared
Jared

Reputation: 26397

>>> 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}

Upvotes: 5

jamylak
jamylak

Reputation: 133504

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}

Upvotes: 1

Related Questions