Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Key(s) corresponding to max(value) in python dict [duplicate]

Let's consider sample dictionaries 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 dictionaries, 90 is the highest. I need to retrieve the key or keys that correspond to it.

What are the possible ways to get this done? Which is the most efficient one, and why?

Note:

  1. Keys and/or values are not in order for the dictionary. The program keeps adding new (key, value) pairs to the dictionary.

  2. There might be more than one key for max(value)

    a) If a dict has only one key corresponding to max(value), then the result should be just a string (i.e. Key). Example: dict2 above should return 'j'

    b) If a dict has more than one key corresponding to max(value), then the result should be list of strings (i.e. keys). Example: dict1 above should return ['j', 'g']

like image 961
Kumar Avatar asked May 15 '13 15:05

Kumar


People also ask

How do I return a key to the highest value in Python?

The simplest way to get the max value of a Python dictionary is to use the max() function. The function allows us to get the maximum value of any iterable.

How do I return a dictionary key to the highest value?

Python find highest value in dictionary By using the built-in max() method. It is provided with the 'alpha_dict' variable to obtain the highest value from and to return the key from the given dictionary with the highest value, the dict. get() method is used.

Can KEY be repeated in dictionary Python?

Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.


2 Answers

Use max() and list comprehension:

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

Create a function:

>>> 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']
like image 131
Ashwini Chaudhary Avatar answered Nov 15 '22 16:11

Ashwini Chaudhary


You can do:

maxval = max(dict.iteritems(), key=operator.itemgetter(1))[1]
keys = [k for k,v in dict.items() if v==maxval]
like image 24
karthikr Avatar answered Nov 15 '22 16:11

karthikr