Dictionaries
Why this matters
Real data is made of records with named fields. A campaign has a name, a budget and a status. A lead has an email and a source. Dictionaries are how Python holds a record. They matter even more for AI work. APIs send and receive data as dictionaries and lists inside each other. And every message you send to an LLM is a small dictionary: {"role": "user", "content": "..."}.
- Store a record as key-value pairs and look values up by key
- Add, change and remove entries, and handle missing keys with .get()
- List a dictionary's keys, values and items
- Read and build nested data: lists of dictionaries, like an LLM chat request
Look things up by name
Think of a contact card. You don't find someone's phone number by counting to the third line. You look for the label "phone". A list finds values by position. A dictionary (dict) finds them by key: a label you choose. Write it with curly brackets, with a colon between each key and its value:
campaign = {
"name": "Spring Sale",
"channel": "search",
"budget": 5000,
"spend": 3120.5,
}
print(campaign["name"])
print(campaign["budget"] - campaign["spend"])
print(len(campaign)) # number of key-value pairs
campaign["budget"] reads as "the value stored under the key "budget"". That's far clearer than remembering that the budget lives at position 2 of a list.
Keys are usually strings, though numbers work too. Each key appears only once. Give an existing key a new value, and you replace the old one. Values can be anything, including lists and other dictionaries. A dictionary remembers the order its keys were added in.
Adding, changing and removing
The same square-bracket syntax reads, changes and adds:
campaign = {"name": "Spring Sale", "budget": 5000, "status": "paused"}
campaign["status"] = "active" # key exists: replace the value
campaign["clicks"] = 5470 # new key: add it
campaign["budget"] += 500 # update using the current value
del campaign["name"] # remove a key and its value
status = campaign.pop("status") # remove it and get the value back
print(campaign)
print(status)
campaign.update({"spend": 3120.5, "clicks": 5600}) # add or replace several at once
print(campaign)