Chapter DPython dictionariesPage 5 of 8

Python dictionaries

Handle failures and retries

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

~13 minFailure handling

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

Debug the chapter step

Debug from evidence. Reproduce one failure at a time, read the full exception or command output, and locate the first place actual state differs from expected state. Do not add retries to deterministic mistakes; fix the path, shape, name, or assumption.

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

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

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.

For the current debug 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 input contract is named fields describing one model run. The visible result is a dictionary with required keys and a safe fallback for an optional version.

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?