Hone

Lessons · Python · sorting with a key

Sort by the thing that matters

key= tells sorted which part of each item to compare. To sort by two things, return a tuple.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Records almost never sort by their whole value: people by surname, files by size, tasks by priority then age. The key function is where the business rule lives.

How to think about it

Ask: if I had to explain the order to someone, what would I say? 'By age, youngest first' becomes key=lambda p: p["age"]. 'By score descending, then name' becomes key=lambda p: (-p["score"], p["name"]).

Worked example

people = [("cy", 31), ("ada", 27), ("bo", 31)]
Name, age.
print(sorted(people, key=lambda p: p[1]))
By age: ada, cy, bo. Ties keep their original order.
print(sorted(people, key=lambda p: (-p[1], p[0])))
Oldest first, then by name: bo, cy, ada.

Your turn

Sort words by length, shortest first.

by_len = sorted(words, key=)

The trap

Sorting numbers stored as strings: '10' comes before '9'. Convert in the key: key=int.

Practise sorting with a key on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.