liveBook · Manning

Sorted

As explained in Python Workout, Second Edition

sorted is a Python built-in function that returns a new list containing the items from an iterable in sorted order.

sorted is a Python built-in that accepts any iterable and returns its elements in sorted order as a new list. It works with strings, lists, tuples, and other iterable objects; sorting a string produces its characters in Unicode order, not another string. section 3.15 section 3.17

Use the result according to the element structure:

  • Join sorted characters to reconstruct a string: ''.join(sorted(value)). section 3.15
  • Pass key=function to sort by a derived value; Python calls the function once for each element and compares its return values. section 4.11
  • Sort records by a field with key=lambda d: d['name'], a named function, or operator.itemgetter('name'). section 4.10 section 4.11
  • Remember that every call returns a list, even when the input is a tuple or another sequence. section 4.22

Alphabetizing dictionaries

Given country records, write `alphabetize_countries` so it returns a new list ordered by each dictionary's `name` value. The core operation is `sorted(countries, key=lambda country: country['name'])`; replace the lambda with `operator.itemgetter('name')` when that expresses the lookup more clearly. 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}]

Use the supplied G7 country records to practice sorting dictionaries by name, population, or size through the key parameter. section 4.10

How Python Workout, Second Edition covers it

How deep it goes
Explains return types and key-call behavior through worked string, list, tuple, and dictionary examples, without implementation internals.
Examples
Uses sorted characters, variable-length strings, country dictionaries, and database-style tuples as practice data.
What it assumes
Assumes familiarity with iteration, sequences, dictionaries, functions, and string methods while reinforcing their shared iterable model.
What you can do after
Apply sorted to iterable data, reconstruct strings with join, and order records through named or inline key functions.
How it connects
Connects sorted with iterables, strings, lists, tuples, str.join, lambda, and operator.itemgetter.

Also explained in

Compare how 5 books explain sorted →

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.