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

dictionary, key, python

Solution

You can do:

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

Problem

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: Keys and/or values are not in order for the dictionary. The program keeps adding new (key, value) pairs to the dictionary. 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']

Original source

Related problems