Skip to content

Python: Get Dictionary Key with the Max Value (4 Ways)

Python Get Dictionary Key with the Max Value Cover Image

In this tutorial, you’ll learn how to use Python to get the dictionary key with max value in a given dictionary, including if multiple keys have the same value. You’ll also learn how to simply get the max value of all keys in a dictionary. You’ll learn how to do this using the operator library, the max() function, and with dictionary comprehensions. You’ll also learn the benefits and the drawbacks of each of these approaches.

Let’s get started!

The Quick Answer: Use the max() function to get the dictionary key with the max values

Quick Answer - Python Dictionary Get Max Value

What are Python Dictionaries?

Dictionaries in Python are one of the main, built-in data structures. They are collections of items, each consisting of a key:value pairs. Python dictionaries are optimized to retrieve values, when the corresponding dictionary key is known.

Values themselves can be repeated, however keys must be unique. Values can also be of any data type (including other dictionaries), while keys must be immutable data types (such as strings, numbers, or tuples).

Let’s take a look at how dictionaries look in Python. They’re created using {} curly brackets and the key:value pairs are separated by commas.

Let’s create a dictionary called ages, which, well, contains the ages of different people:

ages = {
    'Matt': 30,
    'Katie': 29,
    'Nik': 31,
    'Jack': 43,
    'Alison': 32,
    'Kevin': 38
}

We can then access a dictionary item, either by using [] square bracket notation or, better yet, using the .get() dictionary method. Let’s see how we can get the age for Nik:

>> print(ages.get('Nik'))
31

Now that we’ve covered some of the basics of Python dictionaries, let’s take a look at how we can find the max value of a Python dictionary.

How to Get the Max Value of a Python Dictionary

The simplest way to get the max value of a Python dictionary is to use the max() function. The function allows us to get the maximum value of any iterable.

Let’s see how it works with a list, before diving into a more complex example with a Python dictionary:

some_list = [30, 29, 31, 43, 32, 38]
max_value = max(some_list)
print(max_value)

# Returns: 43

What we can see here, is that we’ve passed in an iterable, a list, and were able to return max value of that iterable.

But how does this work with dictionaries?

Let’s give it a try just by passing in the dictionary:

max_value = max(ages)
print(max_value)

# Returns: Nik

This isn’t exactly what we’d expected. We were hoping to return 43, or at least a number!

Python dictionaries come built-in with a .values() method, which extracts the values of our list. If you have a keen eye, you’ll notice that our some_list list contains all the values of our dictionary. We can simply pass in our .values() method into the max function.

Let’s take a look!

max_value = max(ages.values())
print(max_value)

# Returns: 43

What we’ve done here is first extracted all the values from our dictionary, and then passed that iterable into our max() function.

Now let’s take a look at how you can return the corresponding key with a max value in Python!

Check out some other Python tutorials on datagy.io, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

How To Get Dictionary Key with the Max Value in Python

One helpful skill to learn when working with Python dictionaries is how to get the dictionary key that corresponds with the highest value.

The Python max() function actually accepts a parameter to make this much easier: the key= parameter. The way that this parameter works is to define a function that returns a value for each element of the iterable. So, we can simply pass in a function to compare against!

We can use the .get() method we covered earlier to get the max value of a dictionary in Python. You may recall, from the earlier recap of Python dictionaries, that the .get() method is used to return the value for a key. Let’s see what applying this function to our key= parameter does:

ages = {
    'Matt': 30,
    'Katie': 29,
    'Nik': 31,
    'Jack': 43,
    'Alison': 32,
    'Kevin': 38
}

max_value = max(ages, key=ages.get)
print(max_value)

# Jack

We can see here that by passing in key=ages.get that we return the key with the highest value in a Python dictionary.

How to Get Multiple Dictionary Keys with the Max Values in Python

There may be many times when you want to return the key that has the highest value in a Python dictionary. But what if you dictionary has multiple keys that have the highest value?

Unfortunately, the max() function will simply return the first key it finds.

Fortunately, we can find some alternative solutions to this problem!

We can break down our problem as below:

  1. Get the max value
  2. Create a list comprehension that includes a dictionary key if the key’s value is equal to the max value

Let’s see how we can do this:

ages = {
    'Matt': 30,
    'Katie': 29,
    'Nik': 31,
    'Jack': 43,
    'Jill': 43,
    'Alison': 32,
    'Kevin': 38
}

max_keys = [key for key, value in ages.items() if value == max(ages.values())]

print(max_keys)

# Returns: ['Jack', 'Jill']

In the code above, we loop over the key:value pairs in our dictionary and see if the value is equal to the maximum value. If that’s the case, we add it to our list.

Want to learn more? Check out my in-depth tutorial on Python list comprehensions to learn all you need to know! Or, check out my video on the topic below:

How to Get the Max Value From a List of Dictionaries in Python

You may find yourself working often, with lists of dictionaries. In these cases, it can be helpful to know how to get the max value, across all dictionaries in that list of dictionaries.

Doing this is quite easy! We’ll first do this with a for-loop method, followed by a list comprehension. Let’s take a look at the for-loop method first:

ages = [{'Matt': 30, 'Katie': 29}, {'Nik': 31, 'Jack': 43,}, {'Alison': 32, 'Kevin': 38}]

max_age = int()

for dict in ages:
    if max(dict.values()) > max_age:
        max_age = max(dict.values())

print(max_age)

# Returns 43

We can also re-write this as a list comprehension:

ages = [{'Matt': 30, 'Katie': 29}, {'Nik': 31, 'Jack': 43,}, {'Alison': 32, 'Kevin': 38}]

max_age = max([max(dict.values()) for dict in ages])
print(max_age)

# Returns: 43

Conclusion

In this post, you learned how to get the max value from a dictionary in Python. In addition, you learned how to get the corresponding key or keys that have the max value in a dictionary. Finally, you learned how to get the max value from a list of Python dictionaries.

To learn more about the Python .get() method, check out the official documentation here.

Additional Resources

To learn more about related topics, check out these tutorials:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

5 thoughts on “Python: Get Dictionary Key with the Max Value (4 Ways)”

  1. This site helped me a lot in clearing many of the concepts!
    Thankyou so much for such a great effort to provide so many concepts on a single page 🙂

Leave a Reply

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