liveBook · Manning

Map

As explained in Get Programming: Learn to code with Python

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

A map connects one object to another so you can look up the second object using the first. In Python, this data structure is a dictionary, or dict. Each entry has a key, which you look up, and a value, which you get back. Think of a grocery item mapped to the quantity you need. section 27.0 section 27.1

Make and use a grocery map

grocery = {"milk": 1, "eggs": 12, "bread": 2} print(grocery["eggs"]) grocery["milk"] = 2 The braces create a dictionary. Commas separate its entries; in each entry, the key sits left of the colon and its value sits right. Looking up "eggs" gets 12. Assigning a value to the existing key "milk" replaces its old value. section 27.1 section 27.2

Choose a dictionary when you have pairs to connect, then use these operations as you need them:

  • Start with {} and add an entry with d[key] = value. len(d) tells you how many entries there are. section 27.1 section 27.2
  • Use d.pop(key) to remove an entry and get its value back. section 27.3
  • Loop over d.keys() to visit keys and look up their values; d.values() gives you the values directly. section 27.4

A list connects integer positions to items; a dictionary lets you choose keys suited to the pairs you have. Dictionaries can change, but each key must be unique and immutable. Values may be mutable, such as lists of quiz grades. Do not use printed entry order as a substitute for keys: the Python 3.5 examples can display entries in a different order from insertion. section 27.0 section 27.2 section 27.4 section 27.6

Try this: how would you map each song name to its rating, then print only the songs rated 5? The same key–value idea can count words: use each word as a key and increase its count each time it appears. Those counts can also help compare two documents. section 27.6 section 27.5 section 29.0

How Get Programming: Learn to code with Python covers it

How deep it goes
Works through creation, updates, removal, iteration, and key restrictions, but gives only a brief hash-function explanation.
Examples
Uses grocery quantities, student grades, song ratings, word counts, and shape-area functions as examples.
What it assumes
Builds on lists and introduces dictionary keys, values, and creation from zero.
What you can do after
Build it from scratch to store paired data, update entries, count words, and support document comparison.
How it connects
Connects maps to lists, mutability, key–value pairs, frequency counting, and functions.

Also explained in

Compare how 42 books explain Map →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.