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