g↗genai/ learner
Python for AI / Lesson 06

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.

Concept + interactive labBeginner friendly

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:

  1. 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.
  2. KeyError and .get(): what happens when a key is missing. KeyError is 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.
  3. None: Python's built-in "no value here" object. It indicates the absence of data, not an error.
  4. 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.

Running example (toy data)

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
Filing cabinet analogy diagram: a wooden cabinet has three drawers with handle labels 'id', 'topic', and 'priority' acting as keys, with cards pulled out on the right showing the stored values 'T-204', 'billing', and 'high'.
Each key is like a drawer label that points directly to its stored value. You look up a value by its key name, not by counting positions.

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]] raises TypeError: 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 with KeyError: 'owner'.
  • ticket.get("owner", "unassigned") returns the fallback default 'unassigned'.
  • ticket.get("owner") with no second argument returns None without 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.
Reading with brackets halts on missing keys, while .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.
Assignment checks if the key exists: existing keys are replaced in place, while new keys insert an additional pair.

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'.
The first bracket accesses the outer dictionary; the second bracket reads the value stored inside the inner dictionary.

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?

CollectionPrimary lookup mechanismTypical use in Python and AI
listPosition index: queue[0]Ordered sequence of similar items, such as incoming prompt tokens (pieces of words) or a queue of ticket IDs.
dictKey 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.
Choose a list when position and sequence order matter. Choose a dictionary when items represent named attributes of an entity.

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 have 0 as a key?
It raises KeyError: 0, because dictionaries do not look up by numerical index position.
✎ Try it yourselfKnowledge check · Practice only

Practice: Updating and adding pairs.

ticket = {"id": "T-204", "topic": "billing"} ticket["toipc"] = "refund" What is len(ticket) and what is the value of ticket["topic"]?

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:

  1. In panel 1, keep 'topic' and ticket[key] to inspect 'billing'.
  2. Choose 'assignee' and observe brackets halt with KeyError: 'assignee'.
  3. Switch the method to ticket.get(key) (returns None) and then to the default version (returns 'unassigned').
  4. In panel 2, click ticket['priority'] = 'low' and note the length stays 3.
  5. Click ticket['assignee'] = 'Sam' to insert a new pair. Notice the length becomes 4, and reading 'assignee' in panel 1 now succeeds.
  6. 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

Key to look up
How to look up
Python runsticket['topic']
Result'billing'
Found stored value for key 'topic'.

2. Change the ticket

ticket currently has 3 pairs:
{
  'id': 'T-204',
  'topic': 'billing',
  'priority': 'high'
}
Ticket starts with 3 base pairs.

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"}}
Result'pro'
Step 1 reads the inner dict {'name': 'Ana', 'plan': 'pro'}, and step 2 reads 'pro' from it.
✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

run_config = { "model": "gpt-4o", "params": { "temp": "0.7" } } Which line retrieves "0.7" from run_config?
THE TAKEAWAY

Take this with you.

  • Key lookup: Access values by key name with d['key'], which raises KeyError if missing.
  • Safe defaults: Use d.get('key', default) to provide a fallback without halting or mutating the dictionary.
  • Assignment: Assigning with d[key] = value updates 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.
Back to Chapter P1 →