Reputation: 2156
Say I have a dictionary which looks like this:
dct = {'key1':('Hello, Python!', 1), 'key2':(10, 2), 'aa':(9.9, 3)}
How do I return the key which has the highest 2nd value, ie. the highest 2nd value between 1, 2 and 3 is 3, therefore the returned key is:
'aa'
Upvotes: 0
Views: 67
Reputation: 20669
You can use max
.
max(dct.items(),key=lambda x:x[1][1])
# ('aa', (9.9, 3))
If you just want 'aa'
max(dct.items(),key=lambda x:x[1][1])[0]
# 'aa'
Upvotes: 1
Reputation: 367
Sort the dictionary by values (item[1]
when you parse dct.items()
), and especially by the second element of these values (item[1][1]
).
Then your max is the first element of the sorted list.
ordered_keys = [k for k, v in sorted(dct.items(), key=lambda item: item[1][1], reverse=True)]
best = ordered_keys[0]
Upvotes: 1