liveBook · Manning

Key parameter

As explained in Python How-To

A key parameter is a sorting or selection parameter that accepts a callable for deriving a comparison value from each item.

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

How Python How-To covers it

How deep it goes
Explains one-argument key callables, derived comparison values, lambdas, and custom classes, but stops short of callable implementation generally.
Examples
Uses mixed-type values, urgency-ranked task dictionaries, description lengths, and poker cards to demonstrate derived ordering.
What it assumes
Assumes basic lists, iterables, functions, and dictionaries while teaching mixed-type comparison and one-argument callable keys.
What you can do after
Apply it via sort or sorted to order records by extracted fields, choose lambdas for small jobs, and build callable domain mappings.
How it connects
Connects key parameters with sort, sorted, max, min, lambda functions, callables, and pandas apply.

Also explained in

Compare how 2 books explain key parameter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.