Key Max Val Dic Python

How to get the key with the maximum value in a dictionary?

I have spent my morning hours with an important mission: finding the cleanest, fastest, and most concise answer to this question. I realized that many answers on the web use libraries which is not necessary for this simple problem.

In short: use the max function with the key argument. It’s a simple but powerful solution to get the key from a dictionary with the highest value (maximum) – without using any library call:

income = {'John' : 213000,
          'Mary' : 23000,
          'Alice' : 878000}

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

Instead of reading the article, you can also watch the short explainer video:

What is the max function in Python?

Most likely, you already know Python’s max(…) function. You can use it to find the maximum value from any iterable or any number of values. Here are a few examples of using the max function without specifying any optional argument.

# Mary

# 878000

# 99

# [5, 6, 4]

# 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 which you can compare against other objects.

Now, let’s look into the optional arguments of the max function. The max function allows for the optional argument ‘key’. Here is a concise definition of what this argument does:

How exactly does the key argument of the max() function work in Python?

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

Intermezzo: 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 method next() with the following semantics: each time you call next, you get a new element until you got all elements of 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.

Now, you can understand what the key function argument of the max() function does in Python: You pass an iterable as argument for which you want to find the maximum value. Via the optional key argument, you define a function that returns a value for each element in the iterable. The comparison is then 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 simply returns the value multiplied with (-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 the value 16. The second is the parametrized execution. We specify the function ‘inverse’ as the key function. The result of the key function is the basis on which the Python interpreter compares two values to find out the maximum of all values in the iterable (the list [2, 4, 8, 16]). Using the inverse function the Python interpreter does the following mappings:

Original Value
Associated Value: Basis for max()

Now, the Python interpreter calculates the maximum based on these mappings. Clearly, the value 2 (with mapping -2) is the maximum value in the iterable [2, 4, 8, 16] in this case.

Now let’s come back to the initial question:

How to get key with maximum value in 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 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 formulation, we know that the result of our operation has to be a dictionary key. Therefore, our max() function is called on the keys of a dictionary – one of them is the correct solution. Note that max(income.keys()) is really the same as the shorter version max(income).

However, you want to compute the maximum based on another value (not the dictionary key itself). In the last paragraph, you have learned that you can use the optional key function argument to achieve exactly this.

But which function to use? Nothing simpler than that. You want to get the associated value of a certain key. In our case, for John, the dictionary value 213000 should be the basis for all comparisons.

How can you get the value for a certain key in a dictionary? By calling income[‘John’]. However, as a key argument for the max function, you need to specify a function (the bracket notation is not very useful for this). It turns out that the function income.get(‘John’) is doing (almost) the same as income[‘John’]. (The only difference is that it returns ‘None’ for values that are not in the dictionary.) Thus, you can use the function income.get as a key functional argument for the max function.

income = {'John' : 213000,
          'Mary' : 23000,
          'Alice' : 878000}

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

How to get key with minimum value in dictionary?

Do you have understand the previous code snippet? Then, it’s easy to find the key with minimum value in the dictionary. Here is how:

income = {'John' : 213000,
          'Mary' : 23000,
          'Alice' : 878000}

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

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

What are alternative ways to find the key with maximum value in the dictionary?

There are some alternative ways but I found that they are not as beautiful and clean than the above method. However, for comprehensibility, let’s explore a few more ways of achieving the same thing.

In a StackOverflow article, a user compared seven (!) methods of finding the key with maximum value in the dictionary. Here are all seven methods:

def f1():  
     return k[v.index(max(v))]

def f2():
    d3={v:k for k,v in income.items()}
    return d3[max(d3)]

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

def f4():
    return list(filter(lambda t: t[1]==m, income.items()))[0][0]        

def f5():
    return [k for k,v in income.items() if v==max(income.values())][0]    

def f6():
    # same as f4 but remove the max from the comprehension
    return [k for k,v in income.items() if v==m][0]        

def f8():
    return max(income,key=income.get)     

def f9():
     return list(income.keys())[v.index(max(v))]    

def f10():
     return max(income, key=lambda k: income[k])     

# Alice (all outputs)

In a benchmark performed on a large dictionary by the StackOverflow user, the function 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 the following:

income = {'John' : 213000,
          'Mary' : 23000,
          'Alice' : 878000}

# Alice

Where to go from here?

Do you feel like there is a lot more to be learned in Python? I have created a free Python email course. The deal is simple: I will push you — one step at a time — to higher Python levels. It’s learning on autopilot: simple but effective. Join thousands of ambitious coders!