Denferno
Denferno

Reputation: 39

How to get the key of the maxium value in a dictionary and also return the highest number key if there is a duplicate

(sorry for vague title)

dic = {1:20, 2:20, 3:20, 4:10}

I want it to return 3, because that's the highest key number between the three duplicate values in the dictionary.

What I currently have is:

return max(dic, key = dic.get)

But this won't get my desired result and will return 1

Upvotes: 2

Views: 50

Answers (2)

VisioN
VisioN

Reputation: 145428

Alternative to @wim's solution:

k, _ = sorted(dic.items(), key=lambda x: x[::-1])[-1]

Upvotes: 1

wim
wim

Reputation: 363083

Maximize over (value, key) pairs:

k, _ = max(dic.items(), key=lambda item: item[::-1])

dict items are tuples, and tuples are ordered lexicographically.

Upvotes: 6

Related Questions