Chapter DPython dictionariesPage 2 of 8

Python dictionaries

Set up interfaces and contracts

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

~13 minSetup

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

Setup the chapter step

The required setup is: Python 3 is available; no third-party package is needed for dictionary creation, lookup, iteration, or copying. Confirm it before copying code. The contract separates input from output: named fields describing one model run goes in, and a dictionary with required keys and a safe fallback for an optional version comes out. If either side is ambiguous, later debugging will chase the wrong layer.

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

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

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.

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

Read every command or statement before running it. The examples deliberately expose intermediate state so a surprising result has somewhere concrete to point.

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?