A key parameter lets a sorting or selection operation compare derived values instead of the original items. Pass it a callable that accepts one item and returns the value used for ordering or comparison. Python keeps each derived value associated with its original item, then renders the originals in the resulting order. section 3.2.2 section 10.5.3
Choose the simplest callable that expresses the comparison:
- Use a built-in such as str to make mixed values comparable, although lexicographic ordering may not match the intended domain order. section 3.2.2
- Use a named function when sorting needs a readable, reusable, or more involved extraction, such as returning task['urgency']. section 3.2.3
- Use a one-time lambda for a small operation, such as lambda task: task['urgency']; the callable still takes exactly one item. section 3.2.4 section 7.1.2
- Use sorted for any iterable and receive a new sorted list; use list.sort when changing a list in place. section 3.2.4
- Pass a class or another callable when the comparison requires domain-specific conversion, rather than assuming key accepts only ordinary functions. section 10.5.3
Listing 3.4 Sorting tasks by setting a key
def using_urgency_level(task):
return task['urgency']
tasks.sort(key=using_urgency_level, reverse=True)
print(tasks)
# output the following lines (re-arranged for readability):
[{'title': 'Homework', 'desc': 'Physics + Math', 'urgency': 5},
{'title': 'Laundry', 'desc': 'Wash clothes', 'urgency': 3},
{'title': 'Museum', 'desc': 'Egyptian things', 'urgency': 2}]
Sorts task dictionaries by extracting urgency through a named one-argument key function, then reverses the order so the most urgent task appears first. section 3.2.3
Sorting cards with a domain-specific key
A string key can compare mixed cards but gives the wrong semantic order: A appears before J. A custom int subclass maps J, Q, K, and A to 11, 12, 13, and 14, allowing sorted(cards, key=PokerOrder) to produce [1, 10, 'J', 'A']. section 10.5.3

