Python 用键打印字典中的最高值

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

print highest value in dict with key

pythonpython-2.7dictionary

提问by Nishant Nawarkhede

My dict is like,

我的字典就像,

{'A':4,'B':10,'C':0,'D':87}

I want to find max value with its key and min value with its key.

我想用它的键找到最大值,用它的键找到最小值。

Output will be like ,

输出将像,

max : 87 , key is D

最大值 : 87 , 键是 D

min : 0 , key is C

min : 0 , 键是 C

I know how to get min and max values from dict. Is there is any way to get value and key in one statement?

我知道如何从 dict 中获取最小值和最大值。有没有办法在一个语句中获取值和键?

max([i for i in dic.values()]) 
min([i for i in dic.values()])

采纳答案by Alex Thornton

You could use use maxand minwith dict.get:

您可以使用maxmindict.get

maximum = max(mydict, key=mydict.get)  # Just use 'min' instead of 'max' for minimum.
print(maximum, mydict[maximum])
# D 87

回答by Hackaholic

just :

只是 :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.values())
 min(mydict.values())

valueswill give you list of values from the dictionary. maxfunction gives max value. minfunction minimum value

values将为您提供字典中的值列表。max函数给出最大值。min函数最小值

and you want to get key

你想得到钥匙

回答by holdenweb

The clue is to work with the dict's items (i.e.key-value pair tuples). Then by using the second element of the item as the maxkey (as opposed to the dictkey) you can easily extract the highest value and its associated key.

线索是使用字典的项目(键值对元组)。然后通过使用项目的第二个元素作为max键(而不是dict键),您可以轻松提取最高值及其关联键。

 mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)