Dictionaries
A list finds an item by its position. A dictionary finds a value by a name you choose, which is how programs read fields from structured records.
Dictionaries: Looking things up by name.
Think of looking up someone in your phone by "Ana", not by "line 3". A dictionary (dict) in Python works the same way. You will meet these terms in order:
- Key and value: a name you look up (the key) and what is stored under it (the value). Together they form a pair written as
key: value. - KeyError and .get(): what happens when a key is missing.
KeyErroris Python's error for a key that does not exist..get()uses method dot notation (which we met in Strings) to ask safely and return a default instead. - None: Python's built-in "no value here" object. It indicates the absence of data, not an error.
- Nested: an inner dictionary stored as the value inside another dictionary.
Python 3.7 and later preserves the order in which pairs are added, but you still look values up by key name, not by numerical position. Running ticket[0] searches for a key named 0.
A helpdesk application stores each customer request as a dictionary. All values in this base record are plain text strings, with 3 pairs (len(ticket) == 3):
Keys and values: Reading a pair.
A dictionary is written inside curly braces with comma-separated key: value pairs. Put the key inside square brackets to read its stored value. The built-in len() function counts how many pairs are in the dictionary.
ticket = {"id": "T-204", "topic": "billing", "priority": "high"}
ticket['topic'] # 'billing'
len(ticket) # 3, because there are 3 pairs
Asking for a position does not work like a list. ticket[0] raises KeyError: 0 because Python looks for a key equal to the integer 0, and this ticket has none.
Keys must also follow three rules:
- Keys are unique: If a dictionary literal repeats a key, such as
{"topic": "billing", "topic": "tech"}, Python keeps only the last value ('tech'). - Keys are case-sensitive:
"Topic"and"topic"are two different keys. - Keys must be hashable: A hashable value is an immutable object with a fixed fingerprint Python uses for fast lookups (such as strings, integers, or tuples of immutable values). Passing a mutable list like
ticket[[1, 2]]raisesTypeError: unhashable type: 'list'.
Everyday analogy: a telephone contacts list. Searching for "Ana" retrieves her phone number. You search by name, not by line number.
Missing keys: KeyError vs defaults.
Suppose the ticket does not have an "owner" key yet. How you ask determines what happens:
ticket["owner"]halts execution withKeyError: 'owner'.ticket.get("owner", "unassigned")returns the fallback default'unassigned'.ticket.get("owner")with no second argument returnsNonewithout an error.
ticket = {"id": "T-204", "topic": "billing", "priority": "high"}
ticket['owner'] # KeyError: 'owner'
ticket.get('owner', 'unassigned') # 'unassigned'
ticket.get('owner') # None
'owner' in ticket # False (safe membership check)![Filing cabinet diagram illustrating missing key access: looking up missing drawer 'owner' using ticket['owner'] hits a red KeyError stop sign, while ticket.get('owner', 'unassigned') safely returns 'unassigned' as a fallback default.](/_next/image?url=%2F_next%2Fstatic%2Fimmutable%2Fmedia%2Fmissing.241lpthcpm1rh.jpg&w=3840&q=75)
.get() returns a safe default. Neither alters the ticket.You can also test membership safely using the in operator: "owner" in ticket evaluates to False without error. In a plain Python dict, reading with brackets, .get(), or in never modifies the dictionary.
Everyday analogy: asking a library desk for a book. Square brackets are like the librarian stopping and saying "no such book". .get() is like receiving a bookmark stating "not currently available".
Changing existing pairs and adding new ones.
Writing uses square bracket assignment: ticket[key] = value. Python checks whether the key is already present:
- If the key exists: Python updates its value in place.
ticket["priority"] = "low"replaces'high'with'low'. The length remains 3. - If the key is new: Python inserts a new pair.
ticket["assignee"] = "Sam"grows the length from 3 to 4.
ticket = {"id": "T-204", "topic": "billing", "priority": "high"}
# 1. Update existing key
ticket['priority'] = 'low'
len(ticket) # 3 (replaced in-place)
# 2. Insert new key
ticket['assignee'] = 'Sam'
len(ticket) # 4 (new pair inserted)![Three-panel diagram showing assignment behavior: panel 1 updates existing key 'priority' from 'high' to 'low' with length staying 3, panel 2 inserts new key 'assignee' with length growing to 4, and panel 3 shows a typo in ticket['priorty'] = 'low' quietly inserting a new 4th key.](/_next/image?url=%2F_next%2Fstatic%2Fimmutable%2Fmedia%2Fchanging.3hfqkvg_a7unx.jpg&w=3840&q=75)
Beware of typos: If you misspell an intended key, such as ticket["priorty"] = "low", Python does not raise an error. Instead, it quietly creates a new fourth key named "priorty" and leaves "priority" completely unchanged. (Each card above starts from the original 3-pair ticket. Run in order, as below, the ticket ends with 5 pairs.)
ticket = {'id': 'T-204', 'topic': 'billing', 'priority': 'high'}
ticket['priority'] = 'low' # update existing key
ticket['assignee'] = 'Sam' # insert new key
ticket['priorty'] = 'low' # typo: adds a new key
ticket
# {'id': 'T-204', 'topic': 'billing', 'priority': 'low',
# 'assignee': 'Sam', 'priorty': 'low'}
len(ticket)
# 5 (3 pairs, plus 'assignee', plus the misspelt 'priorty')Everyday analogy: drawer labels. Writing on an existing label replaces the label card; writing on a blank drawer adds a new drawer to the cabinet.
Nested dictionaries: Following a path of keys.
A value can itself be another dictionary. To read nested data, provide keys sequentially from left to right, opening the outer dictionary first and then the inner one.
nested_ticket = {
"id": "T-204",
"topic": "billing",
"customer": {"name": "Ana", "plan": "pro"}
}
nested_ticket['customer'] # {'name': 'Ana', 'plan': 'pro'}
nested_ticket['customer']['plan'] # 'pro'
nested_ticket['plan'] # KeyError: 'plan'![Filing cabinet analogy for nested dictionaries: an outer drawer labeled 'customer' holds two inner compartments labeled 'name' (storing 'Ana') and 'plan' (storing 'pro'). Curved arrows demonstrate ticket['customer']['plan'] opening 'customer' first and extracting 'pro' from 'plan'.](/_next/image?url=%2F_next%2Fstatic%2Fimmutable%2Fmedia%2Fnested.28flmi61_-h-t.jpg&w=3840&q=75)
Direct lookup fails: nested_ticket["plan"] raises KeyError: 'plan' because "plan" is located inside the customer record, not as a top-level key of nested_ticket.
Everyday analogy: a postal mailing address. You specify the city, then the street, then the apartment number. Specifying "Apt 4B" alone is meaningless without the building name.
Choosing between a list and a dictionary.
When designing data structures, ask one primary question: How will you primarily look up an item?
| Collection | Primary lookup mechanism | Typical use in Python and AI |
|---|---|---|
list | Position index: queue[0] | Ordered sequence of similar items, such as incoming prompt tokens (pieces of words) or a queue of ticket IDs. |
dict | Key name: ticket['topic'] | Single entity with named fields, such as model configuration hyperparameters (settings that control text generation) or a support ticket. |
Everyday analogy: numbered locker slots vs labelled office pigeonholes. If you want locker 12, you count through the row by numerical position (a list). If you search for the slot marked "HR Department", you look up its named label directly (a dictionary).
![Side-by-side comparison diagram: a list card shows numbered slots 0, 1, and 2 with queue[0] returning 'T-204' by position index, while a dictionary card shows drawer 'topic' with ticket['topic'] returning 'billing' by key name. A summary bar emphasizes: know the position, use a list; know the name, use a dictionary.](/_next/image?url=%2F_next%2Fstatic%2Fimmutable%2Fmedia%2Fchoosing.1vwftkjvbp5ts.jpg&w=3840&q=75)
Quick questions
- You need to store chat history in the exact chronological order messages were sent. Which collection?
- A
list, because messages form an ordered sequence accessed by step. - You need to store model hyperparameters like "temperature" and "top_p". Which collection?
- A
dict, because each parameter is retrieved by its specific setting name. - What happens if you run
ticket[0]on a dictionary that does not have0as a key? - It raises
KeyError: 0, because dictionaries do not look up by numerical index position.
Practice: Updating and adding pairs.
Try the ticket drawer sandbox.
Before you start: the ticket begins with 3 base pairs ('id', 'topic', and 'priority'). In a plain dict, reading never modifies the ticket; assignment updates existing keys or inserts new ones.
Try it in this order:
- In panel 1, keep
'topic'andticket[key]to inspect'billing'. - Choose
'assignee'and observe brackets halt withKeyError: 'assignee'. - Switch the method to
ticket.get(key)(returnsNone) and then to the default version (returns'unassigned'). - In panel 2, click
ticket['priority'] = 'low'and note the length stays 3. - Click
ticket['assignee'] = 'Sam'to insert a new pair. Notice the length becomes 4, and reading'assignee'in panel 1 now succeeds. - Click
ticket['priorty'] = 'low'to see the misspelt typo add an extra key.
Toy sandbox: invented ticket values and a small rule simulator, not a live Python interpreter.
1. Read from the ticket
ticket['topic']'billing'2. Change the ticket
{
'id': 'T-204',
'topic': 'billing',
'priority': 'high'
}3. Nested Ticket Reference
Inspect how Python navigates inner dictionaries step-by-step:
nested_ticket = {"id": "T-204", "topic": "billing", "customer": {"name": "Ana", "plan": "pro"}}'pro'Check your understanding.
Take this with you.
- Key lookup: Access values by key name with
d['key'], which raisesKeyErrorif missing. - Safe defaults: Use
d.get('key', default)to provide a fallback without halting or mutating the dictionary. - Assignment: Assigning with
d[key] = valueupdates existing keys in place or inserts new ones (beware of typo keys). - Nesting & collections: Traverse nested dictionaries sequentially (
d[outer][inner]). Choose a list when sequential order matters; choose a dictionary when items represent named attributes.