Sorting with key
Sort by anything.
Real data is rarely just numbers. You sort people by age, words by length, and products by price. Python's sorted takes a key function, which tells it what to compare.

- People by age
- Words by length
- Products by price
Keys for every job
Key equals len sorts words by their length. A lambda can pull out any field, like the price from each product. And a tuple key sorts by one thing, then another. Here, by category first, then by price from high to low, using a minus sign. We print just the names. Run it.
words = ["kiwi", "banana", "fig", "apple"]
print(sorted(words, key=len))
products = [("pen", "office", 3), ("desk", "office", 120),
("mug", "kitchen", 8), ("kettle", "kitchen", 25)]
print([p[0] for p in sorted(products, key=lambda p: p[2])])
print([p[0] for p in sorted(products, key=lambda p: (p[1], -p[2]))])['fig', 'kiwi', 'apple', 'banana'] ['pen', 'mug', 'kettle', 'desk'] ['kettle', 'mug', 'desk', 'pen']
Key tips
The key function runs once per item, so it's efficient. Use reverse equals true to flip the order. Operator dot item getter is a fast alternative to a lambda. And min and max accept a key too, like the cheapest product, or the longest word.
| key | value |
|---|---|
| key=len | by length |
| key=lambda p: p[2] | by a field |
| (a, -b) | two levels |
| min / max | take key too |
Summary
A key function tells Python what to compare. Use tuples for several levels. Next, stability, and why it matters.
Key takeaways- key=
- lambda
- tuples for ties