关于字典:获取python dict中对应于max(value)的键

Get the Key correspond to max(value) in python dict

本问题已经有最佳答案,请猛点这里访问。

(P)Let's consider a sample dictionary of(key,value)pairs a s follows:(p)字母名称(P)《词典》中的所有价值,90是最高的,我需要将关键的更正撤回。(p)(P)What are the possible ways to get this done.什么是效率和为什么?(p)(P)注:(p)

  • (P)Keys and/or values are not in order for the Dictionary.Program keeps adding new(key,value)pairs to the empty dictionary.(p)
  • (P)There might be more than one key for Max(value)Ex:Decti1 above should return["J","G"]Dict2 above should return'j'(p)(P)(a)如果迪克特只对Max(Value)提出了一个关键的修正案,那么结果应当仅仅是一个打击(i.e.key)(b)如果裁定对Max(Value)有超过一个主要更正,则结果应列为作用力(i.e.keys)。(p)

  • 使用max()和列表理解:

    1
    2
    3
    4
    5
    6
    >>> 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']

    创建函数:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>> 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']

    你可以做到:

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