获取python dict中max(value)对应的Key(s)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16569502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:01:27  来源:igfitidea点击:

Get the Key(s) corresponding to max(value) in python dict

pythondictionarykey

提问by Kumar

Let's consider sample dictionaries of (key, value) pairs as follows:

让我们考虑 (key, value) 对的示例字典如下:

 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}

Of all the values in the dictionaries, 90 is the highest. I need to retrieve the key or keys that correspond to it.

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

What are the possible ways to get this done? Which is the most efficient one, and why?

有哪些可能的方法来完成这项工作?哪个是最有效的,为什么?

Note:

笔记:

  1. Keys and/or values are not in order for the dictionary. The program keeps adding new (key, value) pairs to the dictionary.

  2. There might be more than one key for max(value)

    a) If a dict has only one key corresponding to max(value), then the result should be just a string (i.e. Key). Example: dict2 above should return 'j'

    b) If a dict has more than one key corresponding to max(value), then the result should be list of strings (i.e. keys). Example: dict1 above should return ['j', 'g']

  1. 键和/或值不是按字典顺序排列的。程序不断向字典添加新的(键、值)对。

  2. max(value) 可能有多个键

    a) 如果一个 dict 只有一个 key 对应于 max(value),那么结果应该只是一个字符串(即 Key)。示例:上面的 dict2 应该返回 'j'

    b) 如果一个 dict 有多个键对应于 max(value),那么结果应该是字符串列表(即键)。示例:上面的 dict1 应该返回 ['j', 'g']

采纳答案by karthikr

You can do:

你可以做:

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

回答by Ashwini Chaudhary

Use max()and list comprehension:

使用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']

Create a function:

创建一个函数:

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