I have a dictionary whose components are all 2-tuples (all integers) and I want to find the key to the tuple with the largest second component. How can I do this in Pyth开发者_Go百科on 2.6?
The following will do it (where d
is your dictionary):
max(d.items(), key=lambda(k,v):v[1])[0]
In this solution, the key (if you pardon the pun) is to use the optional key
argument to max
.
aix' answer is a good one. You can achieve the same without using lambdas if you prefer, though:
import operator
m = max(d.iteritems(), key=operator.itemgetter(1))[0]
精彩评论