Get Key with Maximum Value in Dictionary in Python

Last Updated on May 18, 2024 by Roshan Parihar

To get a key with a maximum value in Dictionary in Python, use the max() function and pass two arguments. You can also use a for loop with an if condition for this.

Let’s find out with the examples given below.

How to Get Key With Maximum Value in Dictionary Using max() in Python

If you want to get the maximum key value, you have to use the max() function of Python. The function requires two arguments to pass.

The first argument contains the dictionary variable from where you find the key. The second argument contains the method to get the key using key=myDict.get. Where ‘myDict’ is the dictionary variable in the example.

Example 1

Output

three

The above example contains the Dictionary which contains four elements. Each element contains numeric values. The output contains the key which contains the largest value in the Dictionary.

Using max() with For Loop

In addition to the above examples, you can also use the max() function with a for loop. Firstly, get the max value using values(). After that, use the if condition within the loop to get the key of the maximum value.

Example 2

Output

[‘three’]

The above example shows the output containing the max value in Python. There are four key-value pairs in the Dictionary.

DOWNLOAD Free PYTHON CHEAT SHEET

You may also like to read