KOOTS HOOTS
KOOTS HOOTS

Reputation: 63

How to find multiple maximums in a dictionary

Trying to analyse some strings and compute the number of times they come up. This data is stored in a dictionary. If I were to use the max function only the first highest number encountered would be printed.

count = {"cow": 4, "moo": 4, "sheep": 1}
print(max(count.keys(), key=lambda x: count[x]))
cow

This would yield cow to be the max. How would I get "cow" and "moo" to both be printed

count = {"cow": 4, "moo": 4, "sheep": 1}
cow, moo

Upvotes: 0

Views: 770

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53029

Why not keep it simple?

mx = max(count.values())
print([k for k, v in count.items() if v == mx])
# ['cow', 'moo']

The bracketed expression in line two is a list comprehension, essentially a short hand for a for loop that runs over one list-like object (an "iterable") and creates a new list as it goes along. A subtlety in this case is that there are two loop variables (k and v) that run simultaneously their values being assigned by tuple unpacking (.items() returns pairs (key, value) one after the other). To summarize the list comprehension here is roughly equivalent to:

result = []
for k, v in count.items():
    if v == mx:
        result.append(k)

But the list comprehension will run faster and is also easier to read once you got used to it.

Upvotes: 4

RoadRunner
RoadRunner

Reputation: 26315

Just group the counts with a defaultdict, and take the maximum:

from collections import defaultdict

count = {"cow": 4, "moo": 4, "sheep": 1}

d = defaultdict(list)
for animal, cnt in count.items():
    d[cnt].append(animal)

print(dict(d))
# {4: ['cow', 'moo'], 1: ['sheep']}

print(max(d.items())[1])
# ['cow', 'moo']

Upvotes: 1

Related Questions