liveBook · Manning

Map

As explained in Learn AI-Assisted Python Programming, Second Edition

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

A dictionary stores associations between data by mapping each key to a value. For example, a word-frequency dictionary maps each word to the number of times it appears. Keys must be unique, but values may repeat. section 5.1.3

Use dictionaries to store and work with changing associated data:

  • Access a value with index notation, such as freq['DNA']. Key matching is case-sensitive, so freq['dna'] raises a KeyError when only DNA exists. section 5.1.3
  • Change an existing value with indexing, as in freq['morph'] = 6. section 5.1.3
  • Use methods such as keys(), values(), and pop(), and loop through keys to process every associated value. section 5.1.3

Scrabble letter scores

A points dictionary can map each letter to its score, such as {'a': 1, 'b': 3, 'z': 10}. A scoring function then looks up points[char] for every character and sums the results. For example, num_points('zap') returns 14. section 3.3.4

>>> freq
{'DNA': 11, 'acquire': 11, 'Taxxon': 13, 'Controller': 20, 'morph': 41}
>>> freq.keys()                                                  #1
dict_keys(['DNA', 'acquire', 'Taxxon', 'Controller', 'morph'])
>>> freq.values()                   #2
dict_values([11, 11, 13, 20, 41])
>>> freq.pop('Controller')         #3
20
>>> freq
{'DNA': 11, 'acquire': 11, 'Taxxon': 13, 'morph': 41}

Inspect dictionary contents, retrieve keys and values, remove an entry, and observe the changed mapping. section 5.1.3

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Explains mappings, keys, values, uniqueness, mutability, indexing, methods, iteration, and key errors through interactive examples.
Examples
Demonstrates word frequencies, quarterback passing yards, Scrabble letter scores, method calls, key errors, updates, and iteration.
What it assumes
Assumes familiarity with basic Python values and collections while teaching dictionary terminology and operations through examples.
What you can do after
Apply dictionaries via Python to store associations, retrieve and update values, remove entries, and iterate through mappings.
How it connects
Connects dictionaries with keys, values, indexing, mutability, loops, lists, strings, functions, and file processing.

Also explained in

Compare how 42 books explain Map →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.