Sorting with key functions

Comprehensions & Iteration, lesson 4 of 5

⚡ Comprehensions & Iteration, lesson 4 of 5

Sorting with key functions

Sort, rank and pick winners by any rule you like.

10 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

sorted, min, max and list.sort accept a key function. Python calls it on every item and sorts by the results, while still returning the original items:

  • key=len: by length
  • key=str.lower: alphabetically, ignoring case
  • key=lambda p: p["score"]: by a field
Example

Different orders

Plain sorted puts capitals first ("Z" comes before "a"). key=str.lower fixes that.

Example

Leaderboard

max with a key returns the whole record, not just the score.

Quiz

What does this print?

Tie-breakers. Tuples compare item by item, so a key that returns a tuple sorts by the first value, then the second, and so on. To sort one part descending, negate it (works for numbers).

Example

Highest score, then A to Z

Change the key to lambda s: s[0] to sort by name only.

Example

Sort a dict by its values

counts.get is a function that looks up a key's value, so it works as a key!

Quiz

What does this print?

Exercise

Rank the products

Each product is (name, price, rating). Build:

  1. cheapest_first: product names, lowest price first.
  2. best_rated: product names, highest rating first; on a tie, the cheaper one first.
  3. priciest: the name of the most expensive product (use max with a key).