liveBook · Manning

Map

As explained in Python Workout: 50 ten-minute exercises

A dict is Python's mutable mapping type that associates hashable keys with values.

When related values need names instead of numeric positions, use a dictionary (`dict`). It stores unique, hashable keys alongside values, so code can retrieve information by a meaningful label: a username, menu item, configuration option, or error name. Values may be any objects, including other dictionaries. section 4.0 section 4.23

Common dictionary patterns include:

  • Define a small record or lookup table: `menu = {'sandwich': 10, 'tea': 7}`. section 4.3
  • Retrieve with `d[key]` when the key must exist, or use `d.get(key, default)` to avoid `KeyError` and supply a fallback. section 4.2 section 4.14
  • Test membership with `key in d`, then iterate through keys or key-value pairs with `for key, value in d.items()`. section 4.4 section 4.2
  • Accumulate related measurements, counts, or records by updating values associated with arbitrary keys. section 4.12 section 5.12
  • Transform data with dictionary comprehensions, including filtered dictionaries, reversed mappings, and nested dictionaries. section 7.21 section 7.45

A lookup loop with a running total

MENU = {'sandwich': 10, 'tea': 7} total = 0 while True: order = input('Order: ').strip() if not order: break if order in MENU: total += MENU[order] print(f'{order} costs {MENU[order]}, total is {total}') else: print(f'Sorry, we are fresh out of {order} today.') print(f'Your total is {total}') The dictionary replaces a chain of conditionals: membership checks whether the dish exists, and indexed lookup retrieves its price. Empty input ends the loop. section 4.3 section 4.4

Comparing two dictionaries

def dictdiff(first, second): output = {} all_keys = first.keys() | second.keys() for key in all_keys: if first.get(key) != second.get(key): output[key] = [first.get(key), second.get(key)] return output `dict.keys()` supports set-style union, so each key is examined once. `get` supplies `None` for a missing key, while differing values are recorded in the result. section 4.13 section 4.14

d1 = {'a':1, 'b':2, 'c':3}
d2 = {'a':1, 'b':2, 'c':4}
print(dictdiff(d1, d1))       #1
print(dictdiff(d1, d2))       #2
 
d3 = {'a':1, 'b':2, 'd':3}
d4 = {'a':1, 'b':2, 'c':4}
print(dictdiff(d3, d4))       #3
 
d5 = {'a':1, 'b':2, 'd':4}
print(dictdiff(d1, d5))       #4

Use the worked dictionary-difference listing to trace identical dictionaries, changed values, and keys present on only one side. section 4.13

Dictionaries also provide a bridge between input formats and useful program data. Parse colon-separated account records into `{username: user_id}`, count words while reading a file once, or collect keyword arguments in `**kwargs` and render them as attributes. These patterns keep related data together and make functions easier to compose. section 5.6 section 5.12 section 6.2

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains creation, lookup, membership, iteration, accumulation, comparison, parsing, and hashing, but does not detail dictionary implementation internals.
Examples
Demonstrates menus, rainfall totals, log grouping, file counts, password records, dictionary differences, reversals, and keyword-generated XML.
What it assumes
Assumes basic Python functions, loops, strings, and collections while teaching dictionary access and missing-key handling directly.
What you can do after
Apply it via Python syntax to build lookups, accumulate data, compare mappings, parse records, and transform collections.
How it connects
Connects dictionaries with sets, hashing, comprehensions, functions, file processing, and string methods.

Also explained in

Compare how 42 books explain Map →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.