﻿ How to Get the Smallest or Largest Value of a Dictionary in Python ﻿ # How to Get the Smallest or Largest Value of a Dictionary in Python In this article, we show how to get the smallest or largest value of a dictionary in Python.

So imagine you have a dictionary in Python, which is composed of key-value pairs, as dictionaries are, and the values are numbers.

These numbers could represents the price of products, the price of stocks, the scores of exams, etc.

There could be obvious applications where you may want to find the cheapest/most expensive product, the lowest/highest price of a stock, the lowest or highest exam result.

How can we do this in Python with dictionaries?

We'll show how to do this below.

We'll first show how to simply get the lowest or highest value of a dictionary, in which only the value is returned.

After, we'll show how to return both the key of the value of the smallest or largest item.

So we have a dictionary, beverages, which has some common beverages along with their price.

If you simply want to get the value of the lowest price beverage, you would use the line, min(beverages.values())

This returns a value of 0.99

If you want to get the value of the highest price beverages, you would use the line, max(beverages.values())

This returns the value of 4.99

So we know from this program that the lowest priced beverage is 0.99 and the highest price beverage is 4.99. However, we don't know which item is 0.99 and which is 4.99. Obviously we can look at the dictionary and tell but imagine the dictionary was composed of hundreds or thousands of items. Looking through it wouldn't be easy. Thus, usually when we are working with dictionaries in Python, we want the key returned with the value.

So how do we find the minimum and maximum value of a dictionary while returning the key, so that we know which item is being referenced?

We show this in the following code below.

So we have the same exact dictionary as before.

Now, however, we use the Python zip() function to display both the key and value pairs.

We get the lowest price beverage using the line, min(zip(beverages.values(), beverages.keys()))

And we get the highest price beverage using the line, max(zip(beverages.values(), beverages.keys()))

So from this, it's clear that water is the cheapest beverage you can get at this store.

And a smoothie is the most expensive beverage you can get.

If you're looking to spend the least amount of money, then water is the best drink to get.

Again, with this method, you can see exactly what items are being referenced since we returning the key-value pairs instead of only the value.

And this is how we can get the smallest or largest value of a dictionary in Python.

Related Resources