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









































