liveBook · Manning

Map

As explained in Practices of the Python Pro

A map is an associative data structure that stores key-value pairs and supports retrieving values by key.

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

How Practices of the Python Pro covers it

How deep it goes
Defines mappings, retrieval, sorting, performance, and refactoring applications without descending into dictionary internals.
Examples
Demonstrates state capitals, choice-to-word mappings, and HTTP response-format configuration.
What you can do after
Apply Python dictionaries to retrieve values and simplify choice-based or configuration-driven code.
How it connects
Connects dictionaries with mappings, configuration, conditional logic, functions, sorting, and sets.

Also explained in

Compare how 42 books explain Map →

Related concepts

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