Sorting with key and lambda
sorted() takes a key, a function it calls on each item to get the value to compare, so a short lambda can sort recipes by their minutes or a dictionary's entries by their values, from largest to smallest with reverse=True.
Journeyman · Python · Updated
After this lesson you can
- Sort a list with sorted() and a key function, written as a lambda, from smallest or largest with reverse=True
- Sort a dictionary's entries by their values
Key takeaways
- sorted(items, key=by_minutes) calls by_minutes on each item and sorts the items by what it returns, without changing the items themselves.
- key takes a function's name with no parentheses, because sorted() is the one that calls it, once for each item.
- A lambda is a small function with no name, written where it's needed. lambda recipe followed by a colon and recipe["minutes"] is read "given a recipe, give back its minutes".
- reverse=True sorts from largest to smallest, and items that tie keep the order they had.
- Sorting pantry.items() with a key that gives back each pair's value sorts a dictionary's entries by their values.
Every app sorts: the cheapest flight first, the newest message at the top, the highest score leading the leaderboard. Sorting plain numbers or names works with sorted() as it is. Sorting recipes, students or products needs one more thing from you: what to sort them by. This lesson shows how to say it, which you'll do every time you build a top-ten list or a report.
Pantry Pal, a recipe app, wants its recipes from quickest to slowest, and its pantry from the ingredient you have the most of.
What should sorted() compare?
sorted() gives back a new list in order, from smallest to largest, or from largest to smallest with reverse=True:
minutes = [20, 10, 65, 45]
names = ["Pancakes", "Omelet", "Banana bread", "Chili"]
print(sorted(minutes))
print(sorted(minutes, reverse=True))
print(sorted(names))
[10, 20, 45, 65]
[65, 45, 20, 10]
['Banana bread', 'Chili', 'Omelet', 'Pancakes']
Pantry Pal's recipes aren't numbers or names, though. Each one is a dictionary:
recipes = [
{"name": "Pancakes", "minutes": 20},
{"name": "Omelet", "minutes": 10},
{"name": "Banana bread", "minutes": 65},
]
print(sorted(recipes))
Python stops with TypeError: '<' not supported between instances of 'dict' and 'dict'. Sorting means asking "is this one smaller than that one?" over and over, and Python has no rule for when one dictionary is smaller than another. Should Pancakes come before Omelet because of its name or its minutes? You have to say.
key: say what to sort by
Ask a friend to line up a team for a photo "by height", and they look at each person's height and arrange the people by it. The people move; their heights only decide the order. sorted() works the same way with a key: a function it calls on each item, and the value that function returns is what it sorts by.
def by_minutes(recipe):
return recipe["minutes"]
recipes = [
{"name": "Pancakes", "minutes": 20},
{"name": "Omelet", "minutes": 10},
{"name": "Banana bread", "minutes": 65},
]
for recipe in sorted(recipes, key=by_minutes):
print(recipe["name"], recipe["minutes"])
Omelet 10
Pancakes 20
Banana bread 65
key=by_minutes has no parentheses: you hand sorted() the function itself, and sorted() calls it, once for each recipe. With parentheses, by_minutes() would run right there, with no recipe, and stop with a TypeError. The recipes come back whole; only their order changed. Python's own functions work as keys too: sorted(names, key=len) sorts names from shortest to longest.
lambda: a function with no name
by_minutes is a whole def for one line, used once. A lambda writes a small function right where it's needed: lambda recipe: recipe["minutes"], read "lambda: given a recipe, give back its minutes". The parameter goes before the colon and the value it returns after it, with no def, no name and no return. A lambda holds one expression, which is all a key needs.
recipes = [
{"name": "Pancakes", "minutes": 20},
{"name": "Omelet", "minutes": 10},
{"name": "Banana bread", "minutes": 65},
{"name": "French toast", "minutes": 20},
]
quickest = sorted(recipes, key=lambda recipe: recipe["minutes"])
slowest = sorted(recipes, key=lambda recipe: recipe["minutes"], reverse=True)
print([recipe["name"] for recipe in quickest])
print([recipe["name"] for recipe in slowest])
['Omelet', 'Pancakes', 'French toast', 'Banana bread']
['Banana bread', 'Pancakes', 'French toast', 'Omelet']
Pancakes and French toast both take 20 minutes, and in both lists they stay in the order they had: Pancakes first. Items that tie never swap places, with reverse=True too. In your textbook, a sort that keeps ties in their order is called a stable sort.
Sorting a dictionary by its values
sorted() on a dictionary sorts its keys, by name. To sort the pantry by amount, sort its pairs instead. Each pair from .items() is a tuple, two values in parentheses such as ("eggs", 6): pair[0] is the key and pair[1] is the value.
pantry = {"eggs": 6, "flour": 4, "milk": 2, "butter": 1, "sugar": 3}
print(sorted(pantry))
by_amount = sorted(pantry.items(), key=lambda pair: pair[1], reverse=True)
print(by_amount)
for ingredient, amount in by_amount[:3]:
print(f"{ingredient}: {amount}")
['butter', 'eggs', 'flour', 'milk', 'sugar']
[('eggs', 6), ('flour', 4), ('sugar', 3), ('milk', 2), ('butter', 1)]
eggs: 6
flour: 4
sugar: 3
The key gives back each pair's amount, so the pairs are sorted by amount, most first. by_amount[:3] is a slice, the first three pairs: the pantry's top three. When you want a dictionary back, dict(by_amount) makes one with the keys in that order.
Do it: order recipes by servings
For a party, Pantry Pal lists the recipes that feed the most people first.
recipes: a list of dictionaries, one per recipe, each with a"name"and its"servings".
Your job: write the function by_servings(recipes) so it returns a list of the recipes' names, the most servings first.
- Recipes with the same number of servings keep the order they have in the list.
- It returns the names only, not the dictionaries.
Worked through: Pancakes serve 4, Omelet 1, Banana bread 8 and Chili 4. The most servings first is Banana bread (8), then the two with 4 in their list order, Pancakes then Chili, then Omelet (1): by_servings(recipes) returns ["Banana bread", "Pancakes", "Chili", "Omelet"].
Practiced live on the lesson page: write the Python right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
With a key, sorted() can put anything in order, by whatever you choose, which is every top-ten list, leaderboard and "cheapest first" button you've ever used.