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

















