简体   繁体   English

如何返回字典中具有最大值的键

[英]How to return the key with the largest value in a dictionary

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: 1、2 和 3 之间的第二个最高值是 3,因此返回的键是:

'aa'

Sort the dictionary by values ( item[1] when you parse dct.items() ), and especially by the second element of these values ( item[1][1] ).按值( item[1]解析dct.items() )对字典进行排序,尤其是按这些值的第二个元素( 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]

You can use max .您可以使用max

max(dct.items(),key=lambda x:x[1][1])
# ('aa', (9.9, 3))

If you just want 'aa'如果你只是想要'aa'

max(dct.items(),key=lambda x:x[1][1])[0]
# 'aa'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM