liveBook · Manning

Sorting algorithm

As explained in Python Workout, Second Edition

Sorting is the technique of arranging elements according to an ordering determined by their values or derived comparison keys.

Sorting arranges elements by comparing values or derived keys. Python’s built-in sorted function accepts a key function, applies it once per element, and orders elements by the returned values. section 4.11 section 4.13

Use these patterns when sorting Python data structures:

  • Sort dictionaries by extracting a comparable field such as d['name'], rather than comparing the dictionaries themselves. section 4.11
  • Pass a named function when the key logic deserves a name; use lambda for a short, one-use function. section 4.11 section 4.13
  • Use operator.itemgetter when selecting dictionary fields or positional items provides a concise key function. section 4.10 section 4.11
  • Practice derived ordering by length, absolute value, vowel count, inner-list sum, popularity, or multiple tuple fields. section 4.13 section 4.21

Alphabetize country dictionaries

Define a key function that extracts each dictionary’s name, then pass it to sorted: def by_country_name(d): return d['name']; sorted(COUNTRIES, key=by_country_name). A lambda expresses the same strategy inline: sorted(COUNTRIES, key=lambda d: d['name']). section 4.10 section 4.11

COUNTRIES = [
    {'name': 'Canada', 'size': 9984670, 'population': 38250000},
    {'name': 'Italy', 'size': 301340, 'population': 59110000},
    {'name': 'United Kingdom', 'size': 242495, 'population': 67220000},
    {'name': 'France', 'size': 551695, 'population': 67390000},
    {'name': 'Germany', 'size': 357022, 'population': 83200000},
    {'name': 'Japan', 'size': 377975, 'population': 125700000},
    {'name': 'United States', 'size': 9833517, 'population': 331900000}]

Inspect the country records used for field-based sorting: each dictionary contains a name, size, and population. section 4.10

How Python Workout, Second Edition covers it

How deep it goes
Explains key functions, lambda, and itemgetter through exercises without descending into sorting algorithm internals.
Examples
Uses country dictionaries, string lengths, absolute values, vowel counts, nested-list sums, shell popularity, and multi-field movie records.
What it assumes
Assumes basic Python lists, tuples, dictionaries, and functions while developing function-passing through sorting exercises.
What you can do after
Builds country-sorting functions with named keys, lambdas, and operator.itemgetter.
How it connects
Connects sorting with lists, tuples, dictionaries, higher-order functions, lambda expressions, and operator.itemgetter.

Also explained in

Compare how 18 books explain sorting algorithm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.