0

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
KOOTS HOOTS
  • 63
  • 2
  • 10

2 Answers2

4

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.

Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
  • Thank you! Was looking at the other posts such as [this](https://stackoverflow.com/questions/12402015/print-the-key-of-the-max-value-in-a-dictionary-the-pythonic-way) but they did not seem to talk about more than one maximum. Sorry I am new to this! Could you explain how the code in the print function works? – KOOTS HOOTS Dec 10 '17 at 08:13
1

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']
RoadRunner
  • 25,803
  • 6
  • 42
  • 75