Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Processing Dictionaries With min() and max()

00:00 When it comes to processing python dictionaries with min() and max(), you need to consider that if you use the dictionary directly, then both functions will operate on the keys.

00:26 In these examples, min() returns the alphabetically smallest key in prices, and max() returns the largest one. You can get the same result using the .keys() method on the input dictionary.

00:45 The only difference between this example and the previous one is that the code is more explicit and clear about what you’re doing. Anyone reading the code quickly will realize that you want to find the smallest and largest keys in the input dictionary.

00:58 Another common requirement would be to find the smallest and largest values in a dictionary. Let’s say you want to know the smallest and largest prices.

01:06 In this case, you can use the .values() method.

01:17 Finally, you can also use the .items() method on the input dictionary to find the minimum and maximum key-value pairs.

01:32 Here, min() and max() use Python’s internal rules to compare tuples and find the smallest and largest items in the input dictionary.

01:42 Python compares tuples item by item. For example, to determine if (x1, x2) is greater than (y1, y2), Python first tests if x1 is greater than y1. If this is true, then Python concludes that the first tuple is greater than the second without checking the rest of the items. In contrast, if x1 is less than y1, then Python concludes that the first tuple is less than the second. However, if x1 is equal to y1, then Python compares the second pair of items using the same rules.

02:17 Note that in this context, the first item of each tuple comes from the dictionary keys, and because dictionary keys are unique, the items can’t be equal, so Python will never have to compare the second values.

02:32 In the next section of the course, you’ll take a deeper look at min() and max() by tweaking their behavior.

Become a Member to join the conversation.