Find Minimum and Maximum Values in a Python Dictionary [Tutorial]

Are you wondering how to find the minimum and maximum values in a Python dictionary? Here you will find the answers you are looking for.

The easiest way to find the minimum or maximum values in a Python dictionary is to use the min() or max() built-in functions applied to the list returned by the dictionary values() method. You can also pass just the dictionary to the max() or min() functions but in that case you have to use the optional key argument to identify minimum or maximum based on dictionary values and not on keys.

We will go through multiple ways to solve this problem so you can choose the one you prefer.

Let’s start coding!

How Do You Find the Maximum Value in a Python Dictionary?

Let’s assume that we have created a game and that we are storing the points of all players in a dictionary.

>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 230}

The first thing I can think about to calculate the maximum value in a dictionary would be to use a Python built-in function.

Python provides a built-in function called max() that returns the largest item in an iterable.

Also, one of the methods provided by Python dictionaries is values() that returns a list of all the values in the dictionary.

>>> print(points.values)
<built-in method values of dict object at 0x7f9448181500>

Firstly let’s call the values() method on our dictionary to see what we get back:

>>> print(points.values())
dict_values([100, 450, 230])

Then try to pass this list to the max function…

>>> print(max(points.values()))
450

We got back what we wanted, the maximum value in the dictionary.

In the next section we will see how to get the maximum value in the dictionary while also keep tracked of the key mapped to that value.

Get Maximum Value and Its Key From a Dictionary in Python

In the previous section we have seen that the Python max function can be used with iterables.

Is a Python dictionary an iterable?

A Python dictionary is an iterable because it has the dunder method called __iter__. To verify all the methods that belong to a dictionary you can use the command dir(dict).

>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

Here is what happens if you pass the points dictionary defined in the previous section to the max function:

>>> max(points)
'Kate'

The max function returns the key with maximum value in the dictionary. In this case the keys are compared alphabetically.

This is not what we want considering that we want to get the maximum value in the dictionary and not the maximum dictionary key.

To get the maximum value we have to pass the optional argument key to the max function. The argument key is used to specify a one-argument ordering function.

This is the same approach used with the built-in sorted function.

We pass points.get as the key argument so the max function goes through all the keys in the dictionary and gets the maximum after calling the points.get() method for each key (this method returns the value associated to a given key).

>>> max(points, key=points.get)
'Andy'

Once again…

We are passing points.get to the key argument to get the maximum based on the values in the dictionary and not based on the keys.

This time the max function returns the key ‘Andy’ because it’s the key associated to the highest value in the dictionary (450).

To get the actual value we simply have to retrieve the value mapped to the dictionary key obtained with the previous code:

>>> print(points[max(points, key=points.get)])
450

And if we want to print both key and maximum value we can use the following code…

>>> print("Key associated to the maximum value: {} - Maximum value: {}".format(max(points, key=points.get), points[max(points, key=points.get)]))
Key associated to the maximum value: Kate - Maximum value: 450

To print the previous message we have used the string format method.

How Do You Get All the Keys with the Highest Value in a Dictionary?

In the previous examples, there was only one maximum value in the dictionary.

But what happens if in the previous dictionary we have the same maximum value associated to different keys?

Here is what I mean…

>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 450}

In this case both Andy and Kate have 450 points and when I use the code created in the previous section, here is the result:

>>> print("Key associated to the maximum value: {} - Maximum value: {}".format(max(points, key=points.get), points[max(points, key=points.get)]))
Key associated to the maximum value: Andy - Maximum value: 450

We only get back the key ‘Andy’ and this is not correct.

How can we get back a dictionary that contains both keys associated to the maximum value? (in this case Andy and Kate).

We can start with the maximum value and then identify the keys whose value matches the maximum value.

To create this new dictionary we will use a dictionary comprehension.

So let’s calculate the maximum value first and store it in the variable max_value:

>>> max_value = max(points.values())

Then use a dictionary comprehension to create the new dictionary by using the keys that match the maximum value.

>>> {key:value for key, value in points.items() if value == max_value}
{'Andy': 450, 'Kate': 450}

To understand the comprehension expression above you have to remember what the dictionary items() method returns.

>>> print(points.items())
dict_items([('Jake', 100), ('Andy', 450), ('Kate', 450)])

Does it make sense now?

In the dictionary comprehension, we go through each tuple in the list and we take the key and value from the tuples whose value matches the maximum value.

How to Use the Python Max Function with a Lambda Expression

Let’s go through another way to get the maximum value and the key associated to it from a Python dictionary.

Note: with this approach, we are making the assumption that the maximum value in our dictionary can only be one.

Take the following dictionary:

>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 200}

We will calculate the maximum tuple in the list returned by points.items().

>>> print(points.items())
dict_items([('Jake', 100), ('Andy', 450), ('Kate', 200)])

Here is the result we get by simply applying the max built-in function to the list of tuples above…

>>> max(points.items())
('Kate', 200)

Hmmm….this is not what we want…

We are getting this tuple back from the max function because the function is returning the maximum tuple using the first element of the tuple as ordering criteria.

If you want to provide a different ordering criteria to the max() function we can pass the optional key argument that allows to specify a one-argument ordering function.

In this case, our ordering function will be a lambda that picks the second element in each tuple to identify the maximum tuple.

The second element in a given tuple represents a value in the original dictionary.

The lambda function we will pass is…

lambda data: data[1]

The call to the max function becomes:

>>> max(points.items(), key = lambda data: data[1])
('Andy', 450)

As you can see we are getting back the correct key/value pair from the dictionary based on the fact that 450 is the maximum value.

Using operator.itemgetter() with Max Function to Get the Maximum Value in a Dictionary

There is also another way to write the lambda function we have seen in the previous section:

lambda data: data[1]

This lambda function can be replaced by the operator.itemgetter() function, part of the operator module.

By passing the index 1 to operator.itemgetter() you get back the second item of each tuple in the points.items() list.

>>> import operator
>>> max(points.items(), key = operator.itemgetter(1))
('Andy', 450)

As you can see the itemgetter function is used as key argument to identify the maximum value in the dictionary.

If you only want to get back the maximum value you can retrieve it by accessing index 1 of the tuple returned.

>>> max(points.items(), key = operator.itemgetter(1))[1]
450

Another Way to Find the Maximum Dictionary Value Using a Lambda and the Max Function

Let’s have a look at another way to find the maximum value in a dictionary by using a lambda function together with the max function.

In the previous section, we used the lambda function to identify the maximum second item in each tuple returned by points.items().

This time we will work on the original dictionary points instead of points.items().

We want to define a lambda function that given a key returns the value mapped to that key. Then we will use this lambda as an optional key argument (it will be used as an ordering function by the max function).

The lambda function will be:

lambda dict_key: points[dict_key]

Given the following dictionary…

>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 200}

We can use the max function as shown below:

>>> max_value = max(points, key = lambda dict_key: points[dict_key])
>>> print(max_value)
Andy

Note: in the same way we have seen in the previous section this approach doesn’t work if the same maximum value is assigned to multiple keys.

Note 2: the key argument of the max() function has nothing to do with the dictionary key. To make this clear I have used dict_key in the lambda function.

See this as an exercise to practice the use of dictionaries, lambdas and the max function.

How Do You Find the Minimum Value in a Python Dictionary?

To find the minimum value in a Python dictionary you can use the min() built-in function applied to the result of the dictionary values() method.

This is similar to the approach we have used previously to calculate the maximum value.

Let’s use the following dictionary…

>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 450}

And here is the minimum value in the dictionary calculated using the min() function.

>>> min_value = min(points.values())
>>> print(min_value)
100

And now with a dictionary comprehension and an if statement, we can create a dictionary that contains all the keys that match the minimum value.

>>> {key:value for key, value in points.items() if value == min_value}
{'Jake': 100}

Let’s confirm it also works if multiple keys are mapped to the minimum value.

>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 450, 'Jeremy': 100}
>>> {key:value for key, value in points.items() if value == min_value}
{'Jake': 100, 'Jeremy': 100}

It works!

Find Maximum Value in a Python Dictionary Using an “Inverse” Dictionary

If you think we have gone through enough ways to retrieve the maximum or minimum value in a dictionary, think twice 🙂

I want to show you an alternative approach that is quite different from the ones we have seen so far.

Start from the following dictionary:

>>> points = {'Jake': 100, 'Andy': 450, 'Kate': 230}

Now…

I want to swap keys and values in the dictionary.

You will see why shortly…

The format of the original dictionary is:

{key1: value1, key2: value2, ..., keyN: valueN}

The new dictionary will be:

{value1: key1, value2: key2, ..., valueN: keyN}

Let’s do this first and then you will see how you can use the new dictionary to get the maximum value.

To swap keys and values in the dictionary we can use a dictionary comprehension.

>>> points_swapped = {value:key for key, value in points.items()}
>>> print(points_swapped)
{100: 'Jake', 450: 'Andy', 230: 'Kate'}

Make sure you understand this comprehension before you continue reading.

Now, we can use the max() function with the new dictionary to get the maximum value in the dictionary.

>>> print(max(points_swapped))
450

The same applies to the min() function that returns the minimum value in the dictionary:

>>> print(min(points_swapped))
100

Conclusion

Wow, we have seen lots of different ways to retrieve maximum and minimum values from a Python dictionary.

It has been a great opportunity to review Python concepts like:

  • Built-in functions (min/max) with and without the optional key argument.
  • Dictionary methods: dict.values() and dict.items().
  • Lambda functions.
  • The itemgetter function of the Python operator module.
  • Dictionary comprehensions.

I hope you have found this article useful.

And now, what else would you like to learn?

Let me know in the comments below 🙂

1 thought on “Find Minimum and Maximum Values in a Python Dictionary [Tutorial]”

Leave a Comment