Sub topic 4
Sorting and ranking with key functions
This chapter assumes you can define functions with def, work with lists, tuples and dictionaries, and know that a function can be passed as an argument. It builds on lambda expressions from the previous chapters.
What a key function does
sorted, list.sort, min and max accept a key argument. The key is a function that takes one item and returns the value Python should compare instead of the item itself. Python calls it once for each item, then orders the items by the results.
A lambda is a natural fit, because the key is usually a tiny expression.
pairs = [("apple", 3), ("pear", 1), ("fig", 2)]
print(sorted(pairs, key=lambda p: p[1]))
# [('pear', 1), ('fig', 2), ('apple', 3)]The lambda receives each tuple and returns its second element. The tuples are sorted by that number. The original list is unchanged, because sorted returns a new list.
Key functions with min and max
min and max take the same argument. They return the item whose key is smallest or largest, not the key itself.
pairs = [("apple", 3), ("pear", 1), ("fig", 2)]
print(max(pairs, key=lambda p: p[1])) # ('apple', 3)
print(min(pairs, key=lambda p: p[1])) # ('pear', 1)This is how you rank things. To find the longest word, use max(words, key=len). Notice that len is passed without parentheses and needs no lambda. Any built-in or def function that takes one argument can be a key.
Descending order and ties
Pass reverse=True to sort from largest to smallest.
words = ["kiwi", "fig", "banana", "plum", "apple"]
print(sorted(words, key=len, reverse=True))
# ['banana', 'apple', 'kiwi', 'plum', 'fig']Python's sort is stable. Items with equal keys keep their original relative order. Here kiwi and plum both have length 4, and kiwi stays first because it came first. This is also true with reverse=True.
Sorting by several criteria
Return a tuple from the key. Python compares tuples element by element, so the second value only breaks ties in the first.
people = [("Ana", 31), ("Bo", 25), ("Cy", 31), ("Di", 25)]
ranked = sorted(people, key=lambda p: (-p[1], p[0]))
print(ranked)
# [('Ana', 31), ('Cy', 31), ('Bo', 25), ('Di', 25)]Negating the age gives descending age, while the name sorts ascending. Negation only works for numbers. For strings, use two passes and rely on stability: sort by the secondary key first, then by the primary key.
Sorting dictionaries
Iterating a dictionary yields keys. To rank by value, sort the items() view.
scores = {"ana": 82, "bo": 95, "cy": 78}
top = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
print(top) # [('bo', 95), ('ana', 82), ('cy', 78)]
print(max(scores, key=scores.get)) # boThe second form uses the bound method scores.get as the key. It receives each dictionary key and returns its value.
Common errors
- Calling the function. Writing
key=len(x)orkey=f()passes a result, not a function. Passkey=len. - Mixed types. If keys have different types, such as
intandstr, comparison raisesTypeError. Convert inside the key, for examplekey=lambda v: str(v). - Using
cmp-style functions. Python 3 has nocmpargument. A function that compares two items must be wrapped withfunctools.cmp_to_key. Prefer a key that computes one value per item. - Expecting
list.sortto return a list. It sorts in place and returnsNone. Usesortedwhen you need a new list.
Exercise
Given books = [("Dune", 1965), ("Emma", 1815), ("Ulysses", 1922), ("Beloved", 1987)], write one expression that returns the title of the oldest book, and another that returns the list sorted by title length (shortest first), with ties ordered alphabetically by title.
Show answer
Oldest title: min(books, key=lambda b: b[1])[0] gives 'Emma'. By title length then alphabetically: sorted(books, key=lambda b: (len(b[0]), b[0])) gives [('Dune', 1965), ('Emma', 1815), ('Ulysses', 1922), ('Beloved', 1987)]. The tuple key sorts by length first and uses the title only to break ties between Dune and Emma.