获取密钥对应于python dict中的max(value)

Kum*_*mar 6 python dictionary key

让我们考虑一下(键,值)对的示例字典,如下所示:

 dict1 = {'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28, 'g' : 90}
 dict2 = {'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28}
Run Code Online (Sandbox Code Playgroud)

在字典中的所有值中,90是最高的一个,我需要检索与之对应的密钥.

有什么方法可以完成这项工作.哪个是有效的,为什么?

注意:

  1. 键和/或值不符合字典的顺序.程序不断向空字典添加新(键,值)对.

  2. max(value)可能有多个键Ex:上面的dict1应该返回['j','g']上面的dict2应该返回'j'

    a)如果dict只有一个键对应max(value)那么结果应该只是一个字符串(即Key)b)如果dict有多个键对应max(value)那么结果应该是字符串列表( iekeys).

Ash*_*ary 8

使用max()和列表理解:

>>> dic = {'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28,"k":90}
>>> maxx = max(dic.values())             #finds the max value
>>> keys = [x for x,y in dic.items() if y ==maxx]  #list of all 
                                                   #keys whose value is equal to maxx
>>> keys
['k', 'j']
Run Code Online (Sandbox Code Playgroud)

创建一个功能:

>>> def solve(dic):
    maxx = max(dic.values())
    keys = [x for x,y in dic.items() if y ==maxx] 
    return keys[0] if len(keys)==1 else keys
... 
>>> solve({'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28})
'j'
>>> solve({'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28, 'g' : 90})
['g', 'j']
Run Code Online (Sandbox Code Playgroud)


kar*_*ikr 7

你可以做:

maxval = max(dict.iteritems(), key=operator.itemgetter(1))[1]
keys = [k for k,v in dict.items() if v==maxval]
Run Code Online (Sandbox Code Playgroud)