This post will discuss how to return a key with maximum value in a dictionary in Python.

We can use the in-built function max() to return a key with maximum value in a dictionary in Python. The max() function takes an optional argument called key, that is an ordering function to be used for comparison, and returns the largest item in an iterable. There are several ways to use this function:

1. Using operator.itemgetter() function

We can use the dict.item() function to get the list of items in the dictionary and operator.itemgetter() as an ordering function. The operator.itemgetter() function returns a callable object that fetches an item from its operand using its index. The idea is to use this function to create a custom comparison function that returns the value for a given key from a dictionary. We can then pass this function as an argument for key to max(), which will return the maximum key based on its value. Here is an example of how to use this function:

Download  Run Code

 
This has the advantage over other approaches in that it returns the item with the maximum value, while other functions only return the key with the maximum value.

2. Using dict.get() function

Another option is to use the dict.get() function as the key to the max() function, which returns the key with maximum value when the dictionary iterator is used as iterable. Here is an example of how to use it:

Download  Run Code

 
Here’s an alternate version which uses a lambda function to create a custom comparison function that returns the value for a given key from a dictionary. We can then pass this function as an argument for key to max(), which will return the maximum key based on its value.

Download  Run Code

3. Using Inverse Dictionary

A third option is to invert each key/value pair of the dictionary. For example, dictionary { k1: v1, k2: v2, … , kn: vn} should be transformed into a dictionary { v1: k1, v2: k2, … , vn: kn}. This can be easily done using dictionary comprehension, as shown below:

Download  Run Code

 
Alternatively, we can write:

Download  Run Code

4. Using collections.Counter() class

We can create a Counter object from a dictionary and then use its most_common() function, which returns a list of the most common elements and their counts from the Counter object. We can then access the first element of this list, which will be a tuple containing the key with the maximum value and its count. Here is an example of how to use this function:

Download  Run Code

That’s all about getting a key with maximum value in a dictionary in Python.