⚡ 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 lengthkey=str.lower: alphabetically, ignoring casekey=lambda p: p["score"]: by a field
Different orders
Plain sorted puts capitals first ("Z" comes before
"a"). key=str.lower fixes that.
Leaderboard
max with a key returns the whole record, not just the score.
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).
Highest score, then A to Z
Change the key to lambda s: s[0] to sort by name only.
Sort a dict by its values
counts.get is a function that looks up a key's value, so it works as a key!
What does this print?
Rank the products
Each product is (name, price, rating). Build:
cheapest_first: product names, lowest price first.best_rated: product names, highest rating first; on a tie, the cheaper one first.priciest: the name of the most expensive product (usemaxwith a key).