Lesson · Core Collections
Dictionaries
66 min readDictionaries
Dictionaries map hashable keys to values and preserve insertion order. They are one of Python's most important data structures, so key semantics, lookup patterns, and mutation behavior deserve careful attention.
Learning goals
- Trace the worked example: direct lookup,
getwith a default, assigning a new key, iteratingitems(), and counting throughget(ch, 0) + 1. - Explain what assignment does to an existing key versus a new one, including where the key sits in insertion order.
- Choose between
d[key],get(key, default), andsetdefault(key, default)from what each should do when the key is missing. - Predict where a
KeyErrorbelongs and describe what the default argument substitutes for it. - State the key rules (hashable, stable hash, equality consistency) and the no-size-change rule for iteration.
Mental model
The hash is only a starting point: equal keys must hash equal, and collisions are resolved with equality checks, which is why mutable or equality-unstable objects cannot be keys. Insertion order follows the first insertion, so updating a value never moves its key, and iterating yields keys unless you ask for items().
Hash narrows, equality confirms
lookups never move a key
Mental model
the same mechanism as a compact list
key → hash(key) → probe the table → equality check on collision → value ↓ miss: d[key] raises KeyError, get returns the default, setdefault inserts it ↓ assignment: existing equal key replaces the value and keeps its position ↓ a new key appends in insertion order ↓ iteration: keys by default, (key, value) pairs from items(), size must stay fixed
Core idea
A dictionary is a hash table with a public contract: unique hashable keys map to values, lookup costs one hash plus a few equality checks instead of a scan, and iteration follows insertion order. Missing keys split the methods, since d[key] raises KeyError, get(key, default) returns the default, and setdefault(key, default) inserts it. The counting pattern in the worked example, counts.get(ch, 0) + 1, shows the shape of most dictionary code: read with a fallback, compute, write back.
Key-value model
A dictionary stores associations from unique hashable keys to values. Assigning an existing equal key updates its value rather than creating a second entry.
Creation
Creation in Dictionaries means constructing a new object with valid initial state. Compare literal syntax, constructors, and factory-style APIs where they exist, and note whether construction copies or reuses existing objects.
Lookup
Lookup describes the ordered search Python performs to resolve a name, key, attribute, or other reference. Correct reasoning depends on knowing both the search order and the point where an error or fallback occurs.
Assignment
Assigning to d[key] inserts a new entry or replaces the value of an existing equal key, and the statement never produces a value. A new key appends in insertion order, while updating an existing key keeps its original position.
Deletion
del d[key] removes an entry and raises KeyError when the key is absent, while d.pop(key, default) removes and returns the value, or returns the default instead of raising. Both mutate the dictionary in place.
Membership
Membership uses in and not in to ask whether a value is present. The underlying cost depends on the container protocol and data structure, so list membership and set membership have very different performance profiles.
get()
get() reads a dictionary key while allowing a default result instead of a KeyError. In Dictionaries, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
setdefault()
setdefault() returns an existing dictionary value or inserts a default when the key is missing. In Dictionaries, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
update()
update() merges key-value pairs into a mapping and overwrites matching keys. In Dictionaries, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
keys(), values(), items()
Dictionary view objects reflect later changes to the dictionary. They are iterable views, not detached lists, and items() yields key-value pairs.
Iteration
Iterating a dictionary directly yields its keys in insertion order, while the items() view yields (key, value) pairs that loop targets can unpack. The dictionary size must stay fixed during the loop: inserting or deleting entries raises RuntimeError.
Insertion order
Modern Python dictionaries preserve insertion order as part of the language behavior. Updating an existing key does not normally move it to the end.
Hashable keys
Dictionary keys must be hashable: their hash must remain stable while they are used as keys, and equal keys must have equal hashes. Immutable does not automatically mean hashable, but immutability often makes hashability possible.
Dictionary comprehensions
A dictionary comprehension evaluates a key expression and a value expression for each selected input item. Later duplicate keys overwrite earlier values.
Walkthrough
user["name"]reads the value for the key"name"and printsAda; this direct lookup would raiseKeyErrorif the key were absent, whileuser.get("email", "<missing>")prints<missing>because"email"is not in the dictionary.user["active"] = Trueinserts a new entry: a new key appends in insertion order, so the dictionary now iterates asname,role,active, and a later update of an existing key would keep that key's position.for key, value in user.items():walks the pair view and unpacks each item, printingname Ada,role admin, andactive Truein that order.- The counting loop turns
"banana"into counts:counts.get(ch, 0)yields 0 for a first sighting and the current count otherwise, and adding 1 then writing back ends at{'b': 1, 'a': 3, 'n': 2}. Predict before running: the twouserlookups, the three iterated lines, and the final dictionary.
Experiments to try
- Replace
user.get("email", "<missing>")withuser["email"]and read theKeyError; then say in one sentence what the default argument bought you. - Update an existing key with
user["name"] = "Grace"and printlist(user)before and after; confirm the key's position does not move even though its value changed. - Rebuild the counts with
counts.setdefault(ch, 0) + 1in place ofget, and compare the two lines: both work, but decide which makes the read-compute-write shape clearer. - Trigger the iteration failure: run
for key in user: user["new"] = 1and read theRuntimeError, then explain why changing the size during iteration is different from changing a value.
Common mistakes
- Using a list as a key:
d[[1, 2]] = "x"raisesTypeError: unhashable type: 'list', because a mutable object cannot offer the stable hash that key lookup requires. - Indexing a key that may be absent where
getwas intended:user["email"]raisesKeyErrorand the traceback names the missing key, whilegetwould have returned the fallback. - Changing the dictionary size during iteration: adding or deleting entries inside
for key in d:raisesRuntimeError, because the views expect the table to stay stable while they walk it. - Expecting
update()to return a merged dictionary: it modifies the receiver in place, overwrites matching keys, and returnsNone, so the result must be read from the same name afterward.
Practice: Easy
- Evaluate the two lookups: print
user["name"]anduser.get("email", "<missing>"). Predict both outputs, then replace thegetcall withuser["email"]and record theKeyError. - Add
user["active"] = Trueand printlist(user.keys()); predict where"active"lands in the order. Then runuser["name"] = "Grace"and confirm the order is unchanged. - Run the counting loop on
"banana"and printchand the growingcountsdict inside the loop. Predict the final three counts before the first iteration.
Practice: Medium
- Use
setdefaultto group words by first letter: start withgroups = {}and process["ant", "bee", "bat"]withgroups.setdefault(word[0], []).append(word). Print the result and say whatsetdefaultreturned the first time a letter appeared and what it returned later. - Rewrite the counting loop as a dictionary comprehension where each key is a character and each value is
"banana".count(ch); check the result matches the loop, then explain what happens to duplicate keys in a comprehension. - Delete
user["role"]withdeland then withuser.pop("role", None), running each version from the same starting state. Compare when each raises and whatpopreturns.
Practice: Hard
- Design
group_by(items, key_func)that builds a dict of lists usingsetdefault, then test it on a list of names grouped by first letter and on an empty list. Document the result for empty input before implementing. - Build a failure lab with three entries: a list used as a key (
TypeError), a missing-key lookup (KeyError), and an insert performed insidefor key in d:. Record each error message and explain the rule behind it. - Compare
getandsetdefaultfor two jobs: reading a value with a fallback, and inserting a value only when the key is missing. Write one small function for each job, then state the single behavioral difference that decides between them.
Lesson checklist
- I can trace the worked example and predict every printed line, including the final counts.
- I can choose between
d[key],get, andsetdefaultfrom what should happen when the key is missing. - I can explain why insertion order follows the first insertion and why updating a key does not move it.
- I can state the key rules and the no-size-change rule for iteration.
Remember
A dictionary is a hash table with a friendly contract: unique hashable keys map to values, a lookup costs one hash plus collision checks instead of a scan, and iteration follows insertion order. Missing keys are the main decision point, split across `d[key]` (raises), `get` (falls back), and `setdefault` (inserts). Keep keys hashable and the dictionary size stable while iterating, and most dictionary surprises become questions the contract answers.
Interview angles
What is the main purpose of **Key-value model**?+
A dictionary stores associations from unique hashable keys to values. Assigning an existing equal key updates its value rather than creating a second entry.
What should you pay attention to when using **Creation**?+
Creation in Dictionaries means constructing a new object with valid initial state. Compare literal syntax, constructors, and factory-style APIs where they exist, and note whether construction copies or reuses existing objects.
How does **Lookup** fit into this lesson?+
Lookup describes the ordered search Python performs to resolve a name, key, attribute, or other reference. Correct reasoning depends on knowing both the search order and the point where an error or fallback occurs.
Why can a list not be a dictionary key?+
Keys must be hashable, and a list is mutable, so its hash would have to change as its contents change; Python rejects the attempt with TypeError: unhashable type: 'list'. A tuple containing only hashable values can serve as a key instead.