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']
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.
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.
Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.
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']
You can do:
maxval = max(dict.iteritems(), key=operator.itemgetter(1))[1]
keys = [k for k,v in dict.items() if v==maxval]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With