get key with max value in python dictionary

How to Get Key With Max Value in Dictionary

Python dictionaries are powerful data structures that allow you to store diverse data types as key-value pairs in a compact manner. They can be easily converted into JSON data and transferred to and from other applications or even client side. Sometimes you may need to find the key with maximum value in python dictionary. In this article, we will learn how to get key with max value in dictionary in python.


How to Get Key With Max Value in Dictionary

Let us say you have the following python dictionary.

test = {'a': 1, 'b': 30, 'c': 0}

Let us say you want to obtain key with maximum value from the above dictionary, that is, ‘b’.

There are several ways to do this. We will look at some of them

1. Using max function

Max function is used to get maximum value from a list, tuple, or other group of values in python. But it can also be used to get key with max value from python dictionary. Here is the command to do so.

max(test, key=test.get)

The output of above command will be

'b'

If you want to obtain the max value of above dictionary, you can use either of the following statements.

test[max(test, key=test.get)]
OR
max(test.values())

2. Using operator.itemgetter

You can also use the following command to get key with max value.

import operator
max(test.iteritems(), key=operator.itemgetter(1))[0]

If you are using python 3+,

max(test.items(), key=operator.itemgetter(1))[0]

Please note, if there are two key-value pairs with maximum value, then the above command will return only one key value.

3. Using Inversion

You can also invert the key-value pairs in dictionary to obtain the key of max value. We will use list comprehension for this purpose.

inverse = [(value, key) for key, value in test.items()]

The above statement creates a list of tuples called inverse, where the first item is value and the second item is key. Once you have obtained the inverted dictionary, you can get key of this max value using the following expression.

max(inverse)[1]

In this article, we have learnt how to get key with max value in python dictionary. Out of them, the first two methods are simple and do not create another list in memory.

Also read:

How to Configure Python Flask to Be Externally Accessible
How to Get Difference Between Two Lists in Python
How to Import Other Python File
How to Remove Punctuation from String in Python
How to Do Case Insensitive String Comparison in Python

Leave a Reply

Your email address will not be published. Required fields are marked *