Mateus Moura
Mateus Moura

Reputation: 23

How to identify/print the key with the greatest value in a dictonary?

I've found some similar questions but none has solved my problem. Follow this example:

d={'a': 6, 'b': 3, 'c': 8, 'd': 1}

Now I wanna print the key that has the greatest number (in this case 'c') and the smallest too (in this case 'd'). Realize that what I wanna print is the key, not its value.

Upvotes: 2

Views: 128

Answers (2)

LeadingEdger
LeadingEdger

Reputation: 714

@Mateus, here is another way that doesn't use lambda functions:

d={'a': 6, 'b': 3, 'c': 8, 'd': 1}

# Solution #1 - Using lambda function
print('Min key =', min(d, key=lambda k: d[k]))
print('Max key =', max(d, key=lambda k: d[k]))

# Solution #2 - Using the dictionary get() method
print ('Min key =', min(d, key=d.get))
print ('Max key =', max(d, key=d.get))

Either approach will give the same result:

Min key = d
Max key = c
Min key = d
Max key = c

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195438

Use built-ins min()/max() with custom key= parameter:

d={'a': 6, 'b': 3, 'c': 8, 'd': 1}

print('Min key =', min(d, key=lambda k: d[k]) )
print('Max key =', max(d, key=lambda k: d[k]) )

Prints:

Min key = d
Max key = c

Upvotes: 10

Related Questions