liveBook · Manning

Key parameter

As explained in Python Workout: 50 ten-minute exercises

A parameter accepted by sorting functions that specifies a callable for extracting comparison keys from items.

Sorting becomes more useful when the original items are not already arranged by the value you need. Pass a callable to sorted’s key parameter; Python calls it once per element and orders items by the returned keys. section 3.26

Sort names by last name, then first name

Use a function that extracts a comparison key from each dictionary. A tuple key expresses the two-level ordering directly; a lambda can provide the same behavior inline, while operator.itemgetter offers another valid approach. section 3.11 section 3.15

PEOPLE = [{'first':'Reuven', 'last':'Lerner',
   'email':'reuven@lerner.co.il'},
{'first':'Donald', 'last':'Trump',
   'email':'president@whitehouse.gov'},
{'first':'Vladimir', 'last':'Putin',
   'email':'president@kremvax.ru'}
]

Try the sorting exercise with this PEOPLE sequence, returning dictionaries ordered by last name and then first name. section 3.11

Practice by changing the extracted key:

  • Sort positive and negative numbers by absolute value. section 3.15
  • Sort strings by their number of vowels or lists by the sum of their numbers. section 3.15

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains per-element key invocation and demonstrates tuple keys, lambdas, and itemgetter, without examining sorting internals.
Examples
Demonstrates alphabetizing dictionaries by last and first names, then proposes absolute-value, vowel-count, and nested-sum orderings.
What it assumes
Assumes familiarity with sequences and dictionaries while developing callable and function-object understanding alongside sorting.
What you can do after
Apply it via sorted with regular functions, lambdas, tuple keys, or itemgetter.
How it connects
Connects sorted, lambda expressions, function objects, lists, tuples, dictionaries, and operator.itemgetter.

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 Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.