Chapter 08

Dictionaries

Dicts are ordered since Python 3.7. Key hashing rules. The difference between [] and .get(). Merging with |. Never mutate while iterating.

Questions: 18
Difficulty: ★★★☆☆
Key fact: As of Python 3.7, dictionaries maintain insertion order. This is guaranteed by the language spec, not just a CPython implementation detail. Before 3.7, dict order was undefined.
Access — [] vs .get()
Q 01Predict the Output
d = {"a": 1, "b": 2}
print(d["a"])
print(d.get("b"))
print(d.get("c"))
print(d.get("c", 99))
Output
1 2 None 99
Why? d["c"] would raise KeyError. d.get("c") returns None (safe default). d.get("c", 99) returns 99 (custom default). Use .get() when the key might not exist to avoid KeyError.
Q 02Multiple Choice
d = {"a": 1}
d["b"]
Answer: c) KeyError.

Accessing a non-existent key with [] raises KeyError. This is different from .get() which returns None. Common pattern to avoid: if "b" in d: print(d["b"]) — but better to just use d.get("b").
setdefault & defaultdict
Q 03Predict the Output
d = {"a": 1}
d.setdefault("a", 99)
d.setdefault("b", 99)
print(d)
Output
{'a': 1, 'b': 99}
Why? .setdefault(key, default) sets the key to the default only if the key does NOT already exist. "a" already exists with value 1 — it stays 1, the 99 is ignored. "b" doesn't exist — it's set to 99. It also returns the current value for the key.
Q 04Predict the Output
from collections import defaultdict
d = defaultdict(list)
d["a"].append(1)
d["a"].append(2)
d["b"].append(3)
print(dict(d))
Output
{'a': [1, 2], 'b': [3]}
Why? defaultdict(list) automatically creates an empty list when you access a missing key. No need to check if the key exists first. Extremely useful for grouping items. defaultdict(int) auto-creates 0, defaultdict(set) auto-creates empty set, etc.
Keys, Values, Items
Q 05Predict the Output
d = {"x": 1, "y": 2, "z": 3}
print(list(d.keys()))
print(list(d.values()))
print(list(d.items()))
Output
['x', 'y', 'z'] [1, 2, 3] [('x', 1), ('y', 2), ('z', 3)]
Why? .keys(), .values(), .items() return view objects — they reflect changes to the dict in real time. Wrap in list() to get a snapshot. .items() returns key-value pairs as tuples, perfect for for k, v in d.items().
Q 06Multiple Choice
d = {"a": 1, "b": 2}
keys = d.keys()
d["c"] = 3
print(len(keys))
Answer: b) 3.

Dict views are live — they always reflect the current state of the dict. Adding "c" to the dict is immediately visible through the keys view. This is different from calling list(d.keys()) which creates a static snapshot at that moment.
Merging Dicts
Q 07Predict the Output
a = {"x": 1, "y": 2}
b = {"y": 99, "z": 3}
c = a | b       # Python 3.9+
a |= b          # in-place merge
print(c)
print(a)
Output
{'x': 1, 'y': 99, 'z': 3} {'x': 1, 'y': 99, 'z': 3}
Why? The | operator (Python 3.9+) merges two dicts. When keys conflict, the right-hand dict wins. a | b creates a new dict. a |= b updates a in place. Before 3.9: {**a, **b} was the idiom (right-side wins on conflicts too).
Q 08Predict the Output
a = {"x": 1}
b = {"x": 2, "y": 3}
c = {**a, **b}
d = {**b, **a}
print(c["x"])
print(d["x"])
Output
2 1
Why? {**a, **b} — later entries overwrite earlier ones. b comes last, so b["x"]=2 wins. {**b, **a} — a comes last, so a["x"]=1 wins. The order of spread matters for conflict resolution.
Ordering
Q 09Multiple Choice
d = {}
d["c"] = 3
d["a"] = 1
d["b"] = 2
print(list(d.keys()))
Answer: b) ['c', 'a', 'b'].

Since Python 3.7, dicts preserve insertion order. Keys are returned in the order they were first inserted. This is guaranteed behavior — not an implementation detail. Before 3.7, the order was unpredictable.
Hashing Rules
Q 10Predict the Output
d = {}
d[True] = "bool"
d[1] = "int"
d[1.0] = "float"
print(d)
print(len(d))
Output
{True: 'float'} 1
Why? True == 1 == 1.0 and they all have the same hash. Dict keys are unique by value — so True, 1, and 1.0 are all considered the SAME key. The first one (True) stays as the key, but the value is overwritten each time. One key, three assignments, final value is "float".
Q 11Multiple Choice
d = {[1, 2]: "value"}
Answer: b) TypeError.

Dict keys must be hashable. Lists are mutable and not hashable → TypeError: unhashable type: 'list'. Use a tuple instead: {(1, 2): "value"}. Hashable types: int, float, str, bool, frozenset, tuple (of hashables). Unhashable: list, dict, set.
Mutation During Iteration
Q 12Multiple Choice
d = {"a": 1, "b": 2, "c": 3}
for k in d:
    if k == "b":
        del d[k]
Answer: b) RuntimeError.

Modifying a dict's size while iterating over it raises RuntimeError: dictionary changed size during iteration. Safe fix: iterate over a copy of keys: for k in list(d): or build a new dict: d = {k: v for k, v in d.items() if k != "b"}.
Dict Comprehensions
Q 13Predict the Output
squares = {x: x**2 for x in range(5)}
print(squares)

evens = {k: v for k, v in squares.items() if v % 2 == 0}
print(evens)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16} {0: 0, 2: 4, 4: 16}
Why? Dict comprehension syntax: {key_expr: val_expr for item in iterable if condition}. The first creates x → x² for 0-4. The second filters to only even values (0, 4, 16 are even). Very Pythonic way to transform and filter dicts.
Q 14Predict the Output
d = {"a": 1, "b": 2}
inv = {v: k for k, v in d.items()}
print(inv)
Output
{1: 'a', 2: 'b'}
Why? Swapping keys and values in a comprehension inverts the dict. Works correctly when values are unique and hashable. If values are duplicated, the last one wins (since dict keys must be unique).
pop, update, copy
Q 15Predict the Output
d = {"a": 1, "b": 2, "c": 3}
val = d.pop("b")
print(val)
print(d)
print(d.pop("z", "not found"))
Output
2 {'a': 1, 'c': 3} not found
Why? .pop(key) removes and returns the value. .pop(key, default) returns the default if key not found (no error). Without a default, .pop() on a missing key raises KeyError.
Q 16Predict the Output
d = {"a": 1}
d.update({"b": 2, "a": 99})
print(d)
Output
{'a': 99, 'b': 2}
Why? .update(other_dict) merges in-place — existing keys are overwritten with the new values. "a" was 1, updated to 99. "b" is new, added with value 2. The order is: existing keys maintain their relative order, new keys are appended at the end.
Q 17Multiple Choice
d = {"a": [1, 2]}
e = d.copy()
e["a"].append(3)
print(d["a"])
Answer: b) [1, 2, 3].

dict.copy() is a shallow copy — the dict itself is new, but the values are shared references. e["a"] and d["a"] point to the same list. Mutating through either affects the shared object. Use copy.deepcopy(d) to get fully independent copies.
Q 18Predict the Output
d = {"a": 1, "b": 2}
print("a" in d)
print(1 in d)
print(1 in d.values())
Output
True False True
Why? in on a dict checks keys, not values. "a" in d → True (key exists). 1 in d → False (1 is not a key). 1 in d.values() → True (1 is a value). Key lookup is O(1) via hash. Value lookup is O(n) — it has to scan all values.
← Chapter 07: Tuples Chapter 09: Sets →