Build garageTry it → read → next · ~9 min

Tutorials · Chapter D (4/4) · ~9 min

Python dictionaries

Try it → see it → read → next

Store related facts under useful names, then retrieve and update them in code.

Try yourself

Playground

Dict drill

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

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

Recap

What you just did

DictDrill built the {role, content} shape AI APIs use, then nested it under messages.

Teach

How it works

A dictionary maps each unique key to a value:

model = {
    "name": "tiny-tree",
    "accuracy": 0.84,
    "ready": False,
}

model["accuracy"] = 0.88
model["owner"] = "Maya"
print(model["name"], model.get("version", "unknown"))
  1. Create pairs with {key: value}
  2. Read a known key with square brackets
  3. Update or add by assigning to a key
  4. Use get when a key might be missing

Mental model: a dictionary is a labeled drawer cabinet; the key tells you which drawer to open.

Use it

When you'd use this

  • Representing one training example with named features
  • Counting labels such as {"cat": 12, "dog": 9}
  • Building API messages with role and content fields

Watch out

Watch out

model["version"] raises an error if that key is absent. Use model.get("version") when missing data is expected. Keys must be unique: assigning the same key again replaces its old value rather than creating a second copy.

Try next

Try this next

Add a "labels" key whose value is a list. Append one label, then print only that list.