开发者

Getting the key to the maximum component of a tuple in a dictionary of tuples

开发者 https://www.devze.com 2023-03-19 06:36 出处:网络
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 followi

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]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号