Possible Duplicate:
Getting key with maximum value in dictionary?
Let's say I have a dictionary that is comprised of integer keys and integer values. I want to find the integer key with the highest corresponding value. Is there any built in method to do something like this or do I need to implement some kind of merge/sort algorithm?
By using max() and dict. get() method we can easily get the Key with maximum value in a dictionary. To obtain the maximum value from the dictionary we can use the in-built max() function. In this example, we can use iterable and dict to get the key paired with the maximum value.
We can find the second largest value in a dictionary by sorting the values of the dictionaries and then retrieving the second last element from the sorted list.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
list(sorted(dict. values()))[-2] converts dict_values to list and return the second last element of the sorted list, i.e. the second largest value of dictionary. Was this answer helpful?
You can just use max
>>> x = {1:2, 3:6, 5:4}
>>> max(x, key=lambda i: x[i])
3
Or just:
>>> max(x, key=x.get)
3
There are methods to do that, and preferred way is to use this:
import operator
result = max(your_dict.iteritems(), key=operator.itemgetter(1))[0]
Note, that for your needs operator.itemgetter(1)
could be replaced by lambda x: x[1]
.
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