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 Python 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.