获取键对应于python dict中的max(value) [英] Get the Key correspond to max(value) in python dict
问题描述
dict1 = {'a':10 ,'x':44,'f':34,'h':89,'j':90,'d':28,'g':90}
dict2 = {'a' 'x':44,'f':34,'h':89,'j':90,'d':28}
在字典中的所有值中,90是最高的值,我需要检索与之对应的键。
什么是这样做的可能方式。
注意:
-
键和/或值不符合字典的顺序。程序不断向空字典添加新的(键值)对。
-
max(value)可能有多个键
Ex :上面的dict1应该返回['j','g']
以上的dict2应该返回'j'
a)如果dict只有一个对应于max(value),那么结果应该只是一个字符串(即Key)
b)如果dict有多个键对应于max(value),那么结果应该是字符串列表(iekeys)。
您可以:
maxval = max(dict.iteritems(),key = operator.itemgetter(1))[1]
keys = [k for k,v in dict.items ()if v == maxval]
Let's consider a sample dictionary of (key, value) pairs as follows:
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 dictionary, 90 is the highest one, I need to retrieve the key corresponds to it.
What are the possible ways to get this done. Which is the efficient one and why ?
Note:
Keys and/or values are not in order for the dictionary. Program keeps adding new (key, value) pairs to the empty dictionary.
There might be more than one key for max(value) Ex: dict1 above should return ['j', 'g'] dict2 above should return 'j'
a) If dict has only one key corresponds to max(value) then the result should be just a string (i.e. Key) b) If dict has more than one key corresponds to max(value) then the result should be list of strings (i.e.keys).
You can do:
maxval = max(dict.iteritems(), key=operator.itemgetter(1))[1]
keys = [k for k,v in dict.items() if v==maxval]
这篇关于获取键对应于python dict中的max(value)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!