Python dictionaries
Add observability and tests
A dictionary maps unique, hashable keys to values, making named fields clearer than remembering list positions.
Before you start
Why this matters
Before running anything, predict one observable result from the case: one model run needs a name, accuracy, readiness flag, owner, and optional version. Write the prediction beside the command or code line that should cause it. This makes the session an experiment rather than a transcription exercise.
1Learn the idea
Read
Test the chapter step
Turn the stable example into repeatable checks. Capture the command, input fixture, expected output, and important boundary. Tests should be fast enough to run before every change and precise enough that a failure identifies behavior rather than just saying the chapter broke.
Provide one sample record and a function that validates it. Stable field names become an interface, so changing accuracy to score requires updating every producer and consumer.
Read
Run the working example
model = {"name": "tiny-tree", "accuracy": 0.84, "ready": False}
model["accuracy"] = 0.88
model["owner"] = "Maya"
required = {"name", "accuracy", "ready"}
missing = required - model.keys()
if missing:
raise ValueError(f"missing keys: {sorted(missing)}")
print(model["name"], model.get("version", "unknown"))
print(sorted(model))
Expected evidence:
tiny-tree unknown
['accuracy', 'name', 'owner', 'ready']
The output may include version-specific details such as hashes, paths, fitted thresholds, or final decimal places. Compare the structural facts described here rather than copying placeholders. If the structure differs, stop and inspect the earliest unexpected line.
Read
Read it line by line
- the literal creates three key-value pairs with different value types.
- assignment to
accuracyreplaces its old value, while assignment toowneradds a key. - dictionary views support set-like comparison, so subtraction finds required keys that are absent.
- square brackets demand a key;
getsupplies a fallback when absence is normal.
These lines form one chain: named fields describing one model run becomes a dictionary with required keys and a safe fallback for an optional version. Change only one input first. When several values change together, you cannot tell which change caused the new behavior.
Read
Common errors and fixes
- First failure:
KeyErrormeans square-bracket lookup requested an absent key; fix the input or usegetonly when absence is allowed. Re-run the smallest command that proves the repair. - Second failure:
TypeError: unhashable typemeans a mutable list or dictionary was used as a key. Preserve the failing input as a test when it represents a realistic mistake. - Misleading success: a shallow
.copy()does not clone nested lists, so mutating a nested value can still affect both records. A clean-looking final line cannot cancel contradictory intermediate evidence.
When debugging, copy the exact error text and inspect names, paths, shapes, types, and versions. Explain the cause in one sentence before changing code. That discipline prevents a guessed repair from creating a second defect.
Read
Evidence for this stage
On this page, the practical job is to turn important behavior into repeatable checks. The running case is one model run needs a name, accuracy, readiness flag, owner, and optional version.
For the current test step, save the smallest useful evidence: the relevant command, its output, and the input that produced it. Do not use a screenshot as the only record when text can be copied and searched. Keep generated artifacts separate from source inputs so rerunning the example does not destroy the evidence it is meant to evaluate.
The deliverable for this step is a validated model-record dictionary that can be updated and serialized without ambiguous field positions.
Read
Reflect on the result
Return to your opening prediction. Mark it correct or rewrite it with the condition you missed. Then explain the difference between a successful execution and a trustworthy result for this specific example.
Continue learning · glossary & guides
- Which line or command establishes the current step's most important fact?
- What output would reveal that a shallow
.copy()does not clone nested lists, so mutating a nested value can still affect both records? - Can a new user reproduce a validated model-record dictionary that can be updated and serialized without ambiguous field positions from the stated setup?