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




