Python 从字典中返回最大值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42044090/
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-19 21:08:42  来源:igfitidea点击:

Return the maximum value from a dictionary

pythonpython-2.7dictionarymax

提问by Ophilia

I want to return the maximum value and its key from a dictionary, and I know that something like the following should do the trick

我想从字典中返回最大值和它的键,我知道像下面这样的东西应该可以解决问题

max(list.iteritems(), key=operator.itemgetter(1))

However in case that the maximum value in a dictionary is 6 and it happens that multiple keys have the same value .. it will always return the first one ! how can I make it return all the keys that has the maximum number as values along with the value. Here is an example of a dictionary with the same maximum value:

但是,如果字典中的最大值是 6 并且碰巧多个键具有相同的值..它将始终返回第一个!我怎样才能让它返回所有具有最大数量的键作为值以及值。以下是具有相同最大值的字典示例:

dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}

回答by RomanPerekhrest

The solution using list comprehension:

使用列表理解的解决方案:

dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
max_value = max(dic.values())  # maximum value
max_keys = [k for k, v in dic.items() if v == max_value] # getting all keys containing the `maximum`

print(max_value, max_keys)

The output:

输出:

2.2984074067880425 [3, 4]

回答by Willem Van Onsem

You can first determine the maximum with:

您可以首先确定最大值:

maximum = max(dic.values())

and then filterbased on the maximum value:

然后filter基于最大值:

result = filter(lambda x:x[1] == maximum,dic.items())

Example in the command line:

命令行中的示例:

$ python2
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
>>> maximum=max(dic.values())
>>> maximum
2.2984074067880425
>>> result = filter(lambda x:x[1] == maximum,dic.items())
>>> result
[(3, 2.2984074067880425), (4, 2.2984074067880425)]

Given you want to present the list of keysare a nice list and the value, you can define a function:

鉴于您想显示键列表是一个不错的列表和值,您可以定义一个函数:

def maximum_keys(dic):
    maximum = max(dic.values())
    keys = filter(lambda x:dic[x] == maximum,dic.keys())
    return keys,maximum

which returns a tuple containing the list of keys and the maximum value:

它返回一个包含键列表和最大值的元组:

>>> maximum_keys(dic)
([3, 4], 2.2984074067880425)