python · level 2 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Hand sorted a and it sorts by your rule.
Real data often comes as a list of records: one dictionary per film, pet or product. sorted cannot compare two dictionaries by itself. It needs to know which part matters.
Write a key function that takes one and returns the value to sort by, like its price. Then pass its name: sorted(snacks, key=by_price). Leave the brackets off, because sorted calls it for you, once per item.
max and min take a key too, so max(snacks, key=by_price) finds the priciest record.
def by_price(snack):
return snack["price"]
snacks = [
{"name": "flapjack", "price": 1.6},
{"name": "apple", "price": 0.5},
{"name": "crisps", "price": 0.9},
]
for snack in sorted(snacks, key=by_price):
print(snack["name"], snack["price"]) Inside its brackets, a list can spread over several lines to stay readable.
guess first
Shortest word first. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
fruit = ["banana", "fig", "kiwi"]
print(sorted(fruit, key=len))
print(max(fruit, key=len))
your turn
Your turn. Pick tonight's film.
Finish the key function so it returns a film's rating. Then sort with it so the highest rating comes first. Inside the f-string, the keys use single quotes, so they do not end the string early.
fix it
The cheapest item finder crashes. Can you fix it?
- Read the error:
by_pricewas called with nothing in its brackets. Where does that happen? key=wants the function itself, somincan call it once per item. The brackets call it straight away.- Remove the brackets after by_price on line 4, then run.
nailed it
you sorted by your own rules. :D
- A key function turns each item into the value to sort by.
- Pass the function's name with no brackets:
key=by_price. sorted,maxandminall accept akey.
new words in your collection
- record
- key function
This lesson isn’t saved. A free account remembers every lesson you finish.