【问题标题】:Get the Key(s) corresponding to max(value) in python dict [duplicate]获取与python dict中的max(value)对应的Key [重复]
【发布时间】:2013-05-10 06:54:28
【问题描述】:

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

 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}

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

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

注意:

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

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

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

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

【问题讨论】:

  • 返回字符串或字符串列表似乎可能会导致以后不必要的分支。 90% 的情况下,你最好总是返回一个列表。

标签: python dictionary key


【解决方案1】:

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

创建一个函数:

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

【讨论】:

    【解决方案2】:

    你可以这样做:

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

    【讨论】:

    • 如果 dict 对应的 max(val) 有多个键,则它不起作用。有关详细信息,请参阅上面更新的 dict1 和 dict2 定义。
    • 您的新代码不起作用,因为maxval 不是最大值,而是达到最大值的键之一。
    • @DSM :) 大错特错!!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多