Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding largest value in a dictionary [duplicate]

Tags:

python

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?

like image 561
user1427661 Avatar asked Sep 22 '12 04:09

user1427661


People also ask

How do you find the largest value in a dictionary?

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.

How do you find the second highest value in a dictionary?

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.

Can dictionary have duplicate values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

How do we find highest 2 values in a dictionary Python?

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?


2 Answers

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
like image 117
verdesmarald Avatar answered Sep 17 '22 10:09

verdesmarald


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

like image 30
Tadeck Avatar answered Sep 21 '22 10:09

Tadeck