How to Get the Key with Maximum Value in a Python Dictionary?

5/5 - (1 vote)
How to get the key with the maximum value in a dictionary?

I have spent my morning hours on an important mission. What is the cleanest, fastest, and most concise answer to the following question:

💬 How do you find the key with the maximum value in a Python dictionary? 

Most answers on the web say you need to use a library but this is not true! Instead, you can simply apply the following solution to this problem:

To find the key with maximum value in a Python dictionary d, call max(d, key=d.get). This returns the key with maximum value after applying the dict.get(k) method to all keys k to get their associated values.

Here’s a minimal example:

income = {'Anne' : 1111,
          'Bert' : 2222,
          'Cara' : 9999999}

print(max(income, key=income.get))
# Cara

The max() function goes over all keys k, in the dictionary income and takes the one that has maximum value after applying the income.get(k) method. The get() method returns the value specified for key k in the dictionary.

In the remaining article, you’ll learn the answer to a couple of related questions so, in the end, you’ll know dictionaries much better:

  • How to Get the Maximum Value in a Python Dictionary?
  • How to Get the Key with Maximum Value in a Python Dictionary?
  • How to Get the Maximum Key in a Python Dictionary?
  • How to Get the Key with Maximum Value in a Python Dictionary?
  • How to Get the Highest and Lowest Value in a Python Dictionary?

But before we start, feel free to check out my best-selling book on building an exciting career using nothing but your Python skills and a notebook:

Do you want to develop the skills of a well-rounded Python professional—while getting paid in the process? Become a Python freelancer and order your book Leaving the Rat Race with Python on Amazon (Kindle/Print)!

Leaving the Rat Race with Python Book

What’s the Max Function in Python?

Most likely, you already know Python’s max() function. You can use it to find the maximum value of any iterable or any number of values.

The max() function returns the maximum of the provided arguments. You can pass either an arbitrary number of values, comma-separated, or an iterable as arguments. An optional key function argument allows you to customize the calculation of the maximum by explicitly defining the weight of each value in the iterable that is used as a basis of comparison.

Learn more in our ultimate guide on the max() function on the Finxter blog here.

Python max() — A Simple Illustrated Guide

Why don’t we quickly glance over a couple of basic examples without the key argument for starters?

# Key that starts with 'largest' letter of the alphabet
# Mary

# Largest value in the dictionary income
# 878000

# Largest value in the given list
# 99

# Compare lists element wise, max is first list to have a larger
# element 
# [5, 6, 4]

# Largest value in the given sequence of numbers
# 123

So far so good. The max function is very flexible. It works not only for numbers but also for strings, lists, and any other object you can compare against other objects.

Now, let’s look at the optional arguments of the max function. One of them is 'key'. Let’s find out what it does.

How Does the Key Argument of Python’s max() Function Work?

The last examples show the intuitive workings of the max function: you pass one or more iterables as positional arguments.

🎓 What are Iterables? An iterable is an object from which you can get an iterator. An iterator is an object on which you can call the next() function. Each time you call next(), you get the next element until there are no more elements left in the iterator. For example, Python uses iterators in for loops to go over all elements of a list, all characters of a string, or all keys in a dictionary.

When you specify the key argument, define a function that returns a value for each element of the iterable.

Then each element is compared based on the return value of this function, not the iterable element (the default behavior).

Here is an example:

lst = [2, 4, 8, 16]

def inverse(val):
   return -val

# 16

print(max(lst, key=inverse))
# 2

We define a function inverse() that returns the value multiplied by -1.

Now, we print two executions of the max() function.

  • The first is the default execution: the maximum of the list [2, 4, 8, 16] is 16.
  • The second uses key. We specify inverse as the key function. Python applies this function to all values of [2, 4, 8, 16]. It compares these new values with each other and returns the max.

Using the inverse() function Python does the following mappings:

Original Value  Value after inverse() applied as the basis for max()

Python calculates the maximum based on these mappings. In this case, the value 2 (with mapping -2) is the maximum value because -2 > -4 > -8 > -16. 

Now let’s come back to the initial question:

How to Get the Key with the Maximum Value in a Dictionary?

We use the same example as above. The dictionary stores the income of three persons John, Mary, and Alice. Suppose you want to find the person with the highest income.

In other words, what is the key with the maximum value in the dictionary?

Now don’t confuse the dictionary key with the optional key argument of the max() function. They have nothing in common – it’s just an unfortunate coincidence that they have the same name!

From the problem, we know the result is a dictionary key. So, we call max() on the keys of the dictionary. Note that max(income.keys()) is the same as max(income).

✏️ Resource: To learn more about dictionaries, check out our article Python Dictionary – The Ultimate Guide.

However, we want to compare dictionary values, not keys. We’ll use the key argument of max() to do this. We must pass it a function but which? 

To get the value of 'Anne', we can use bracket notation – income['Anne']. But bracket notation is not a function, so that doesn’t work.

Fortunately, income.get('Anne') is similar to income['Anne'] and it is a function! The only difference is that it returns None if the key is not in the dictionary.

So we’ll pass that to the key argument of max().

income = {'Anne' : 1111,
          'Bert' : 2222,
          'Cara' : 9999999}

print(max(income, key=income.get))
# Cara

How to Get the Key with the Minimum Value in a Dictionary?

If you understood the previous code snippet, this one will be easy.

To find the key with minimum value in the dictionary we use the min(income, key=income.get) function.

income = {'Anne' : 1111,
          'Bert' : 2222,
          'Cara' : 9999999}

print(min(income, key=income.get))
# Anne

The only difference is that we use the built-in min() function instead of the built-in max() function. That’s it.

Related Tutorials

Find the Key with the Max Value in a Dictionary – Alternative Methods

There are lots of different ways to solve this problem. They are not as beautiful or clean as the above method. But, for completeness, let’s explore some more ways of achieving the same thing.

In a StackOverflow answer, a user compared nine (!) different methods to find the key with the maximum value in a dictionary.

Here they are:

# Convert to lists and use .index(max())
def f1(): 
    return k[v.index(max(v))]

# Dictionary comprehension to swap keys and values
def f2():
   d3={v:k for k,v in income.items()}
   return d3[max(d3)]

# Use filter() and a lambda function
def f3():
   return list(filter(lambda t: t[1]==max(income.values()), income.items()))[0][0]   

# Same as f3() but more explicit
def f4():
   return list(filter(lambda t: t[1]==m, income.items()))[0][0] 
# List comprehension
def f5():
   return [k for k,v in income.items() if v==max(income.values())][0]  
# same as f5 but remove the max from the comprehension
def f6():
   return [k for k,v in income.items() if v==m][0]   
# Method used in this article
def f7():
   return max(income,key=income.get)    

# Similar to f1() but shortened to 2 lines
def f8():
    return list(income.keys())[v.index(max(v))] 
# Similar to f7() but use a lambda function
def f9():
    return max(income, key=lambda k: income[k])    

# Cara (all outputs)

In a benchmark performed on a large dictionary by the StackOverflow user, f1() turned out to be the fastest one.

So the second-best way to get the key with the maximum value from a dictionary is:

income = {'Anne' : 1111,
          'Bert' : 2222,
          'Cara' : 9999999}

# Cara

Find Key with Longest Value in Dictionary

We know how to find the maximum value if the values are numbers. What about if they are lists or strings?

Let’s say we have a dictionary that records the number of days each person worked this month. If they worked a day, we append 1 to that person’s list. If they didn’t work, we don’t do anything.  At the end of the month, our dictionary looks like this.

days_worked = {'Anne': [1, 1, 1, 1],
               'Bert': [1, 1, 1, 1, 1, 1],
               'Cara': [1, 1, 1, 1, 1, 1, 1, 1]}

The total number of days worked each month is the length of each list.

If all elements of the two lists are the same (as is the case here), they are compared based on their length.

# Length 2 is less than length 4
>>> [1, 1] < [1, 1, 1, 1]

So we can use the same code we’ve been using in the article to find the key with the maximum value.

>>> max(days_worked, key=days_worked.get)

If we update our dictionary so that Bert has worked the most days and apply max() again, Python returns 'Bert'.

>>> days_worked = {'Anne': [1, 1, 1, 1],
                   'Bert': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                   'Cara': [1, 1, 1, 1, 1, 1, 1, 1]}

# Bert has now worked the most
>>> max(days_worked, key=days_worked.get)

Find Key With Max Value in a List of Dictionaries

Let’s say we have three dictionaries containing income information. We want to find the key with the max value from all three dictionaries. 

income1 = {'Anne': 1111,
           'Bert': 2222,
           'Cara': 3333}

income2 = {'Dani': 4444,
           'Ella': 5555,
           'Fred': 6666}

income3 = {'Greg': 7777,
           'Hope': 8888,
           'Igor': 999999999999}

list_of_dicts = [income1, income2, income3]

We can see that 'Igor' has the highest income so we expect that to be returned.

There are several ways to do this.

To get the key with maximum value in a list of dictionaries, first merge all dictionaries by means of a dict.update() method in a for loop iterating over the list of all dictionaries. Then with the key-value pairs in one large dictionary d, call max(d, key = dict.get) to get the key of the dictionary with the maximum value.

Here’s a simple example:

# Initialise empty dict
>>> big_dict = {}

# Use for loop and .update() method to add the key-value pairs
>>> for dic in list_of_dicts:

# Check the result is as expected
>>> big_dict
{'Anne': 1111,
'Bert': 2222,
'Cara': 3333,
'Dani': 4444,
'Ella': 5555,
'Fred': 6666,
'Greg': 7777,
'Hope': 8888,
'Igor': 999999999999}

# Call max() and specify key argument
>>> max(big_dict, key=big_dict.get)

How to Get the Maximum Value in a Python Dictionary?

To get the maximum value in a Python dictionary d, call max(d.values()). This first obtains an iterable of all dictionary values with d.values() and passes it into the max() function that finds the single maximum value.

Here’s an example that gets the maximum integer value from the dictionary values:

d = {'Anne': 24,
     'Alice': 19,
     'Bob': 35}

max_val = max(d.values())

# 35

How to Get the Maximum Key in a Python Dictionary?

To get the maximum key in a Python dictionary d, call max(d) or max(d.keys()). Both are equivalent because they both pass the iterable of keys into the max() function that gets the max key.

Here’s an example that gets the maximum string from the dictionary keys:

d = {'Anne': 24,
     'Alice': 19,
     'Bob': 35}

# 'Bob'

# 'Bob'

How to Get the Highest and Lowest Value in a Python Dictionary?

To get the highest and lowest value in a Python dictionary d, call the functions max(d) and min(d), respectively.

d = {1: 'a',
     0: 'b',
     2: 'c'}

# 2

# 0

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!