Chapter DPython dictionariesPage 1 of 8

Python dictionaries

Define the lab goal and success criteria

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

~13 minLab goal

1Try it yourself

Playground

Dict drill

Chat APIs speak in dicts. Fill the missing key, then nest a messages list.

{ "???": "assistant", "content": "Hello!" }

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.

2Learn the idea

Read

Explain the chapter step

Begin by writing the success condition in observable terms. For this case, success is not familiarity with the vocabulary; it is producing a validated model-record dictionary that can be updated and serialized without ambiguous field positions. Record the starting state so you can distinguish an improvement from a result that was already present.

On this page, the practical job is to state a measurable outcome before changing anything. The running case is one model run needs a name, accuracy, readiness flag, owner, and 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

Assert the required-key difference is empty, accuracy is numeric and between zero and one, and ready is a real Boolean rather than the string 'False'. Test both present and absent optional versions.

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

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

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 KeyError means square-bracket lookup requested an absent 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?