Chapter DPython dictionariesPage 8 of 8

Python dictionaries

Mastery: ship checklist

A dictionary maps unique, hashable keys to values, making named fields clearer than remembering list positions.

~13 minMastery check

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

Ship the chapter step

Shipping means handing off evidence, not only source code. 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. Rebuild or rerun from the documented starting point. If another person needs an undocumented fact from your machine, the handoff is incomplete.

Keep the example small enough to inspect manually. Small does not mean careless: boundary values, file locations, feature order, and held-out data still determine whether the result means what you claim.

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

  1. the literal creates three key-value pairs with different value types.
  2. assignment to accuracy replaces its old value, while assignment to owner adds a key.
  3. dictionary views support set-like comparison, so subtraction finds required keys that are absent.
  4. square brackets demand a key; get supplies 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: KeyError means square-bracket lookup requested an absent key; fix the input or use get only when absence is allowed. Re-run the smallest command that proves the repair.
  • Second failure: TypeError: unhashable type means 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

The deliverable for this step is a validated model-record dictionary that can be updated and serialized without ambiguous field positions.

For the current ship 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.

Do not log entire dictionaries if they may contain tokens or personal data. Select safe fields explicitly. When dictionaries cross an API boundary, document a schema instead of accepting arbitrary keys.

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.

Checking tutor…

Continue learning · glossary & guides
  1. Which line or command establishes the current step's most important fact?
  2. What output would reveal that TypeError: unhashable type means a mutable list or dictionary was used as a key?
  3. Can a new user reproduce a validated model-record dictionary that can be updated and serialized without ambiguous field positions from the stated setup?