×

python · level 2 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.