A dictionary is a mapping from keys to values. Give each item a key, then retrieve its associated value when you need it. For example, a state-capitals dictionary connects "Alabama" with "Montgomery" and lets you collect or sort the values. section 1.7.1
Dictionaries become especially useful when they replace repeated conditional logic:
- Map choices to outcomes, such as 'A' to 'apples' and 'B' to 'bats', then retrieve the outcome with choices[choice]. section 7.1.2
- Represent configuration, such as accepted response formats mapped to JSON or XML responses, and select a fallback when a key is unknown. section 9.2.1
- Use dictionary access to fetch a specific item efficiently; iterating through all items still depends on the number of entries. section 4.2.1
Replace conditionals with a mapping
Instead of adding another elif branch for every choice, define choices = {'A': 'apples', 'B': 'bats'} and format the result with choices[choice]. Adding a new case then means adding one mapping entry. section 7.1.2
Listing 1.1. Getting the United States capitals in alphabetical order
>>> us_capitals_by_state = { #1
'Alabama': 'Montgomery',
'Alaska': 'Juneau',
...
}
>>> capitals = us_capitals_by_state.values() #2
dict_values(['Montgomery', 'Juneau'])
>>> capitals.sort() #3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict_values' object has no attribute 'sort'
>>> sorted(capitals) #4
['Albany', 'Annapolis', ...]
Inspect a short interactive example that builds a state-capitals dictionary, obtains its values, demonstrates an unsuccessful direct sort, and uses sorted(capitals) instead. section 1.7.1









































