Module 08 — Dictionaries
Looking things up by name instead of by position — key/value storage.
Prerequisite: Module 07 — Tuples
After this lesson, you will be able to
- Create dictionaries and access, add, and update values by key
- Loop through keys, values, and key-value pairs
- Use get() to safely look up a key that might not exist
- Build a word-frequency counter using a dictionary
Concept & Syntax
A dictionary stores data as key → value pairs, letting you look things up by a
meaningful name instead of a numeric position. Where a list answers "what's at position 2?", a dictionary
answers "what's stored under the key 'age'?" — a much more natural fit for real-world records like
a user profile or a product listing.
person = {"name": "Ada", "age": 28}
person["age"] # 28
person["email"] = "a@x.com" # add a new key
person.get("phone", "N/A") # safe lookupExamples
Creating and reading a dictionary Very Easy
person = {"name": "Ada", "age": 28}
print(person["name"])
print(person["age"])Square brackets with a key — not an index — retrieve the associated value.
Adding and updating Easy
person = {"name": "Ada"}
person["age"] = 28
person["age"] = 29
print(person)Assigning to a new key adds it; assigning to an existing key overwrites its value.
get() for safe lookups Intermediate
person = {"name": "Ada"}
print(person.get("age", "Unknown"))person["age"] would raise a KeyError since 'age' doesn't exist. get(key, default) returns the default instead of crashing.
Looping through a dictionary Real World
prices = {"apple": 0.5, "bread": 2.3, "milk": 1.2}
for item, price in prices.items():
print(f"{item}: ${price}").items() gives you both the key and value together on each pass of the loop.
Word counter Challenge
text = "the cat sat on the mat the cat ran"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)This classic pattern uses get(word, 0) to start any new word at 0, then adds 1 every time it's seen again.
Visual Explanation
💡 Why does this work?
Read the concept explanation above again slowly, line by line — every keyword there maps directly onto a line of code in the examples. If it still doesn't click, re-run the traced example (if this lesson has one) one step at a time.
🔍 What happens internally? (advanced)
Under the hood, Python compiles your source into bytecode and runs it on a virtual machine (the CPython interpreter). Variables are names in a namespace dictionary pointing at objects in memory — which is exactly what the memory panel in the tracer above is showing you.
Common Mistakes
Accessing a missing key with square brackets crashes the program instead of failing gracefully.
person = {"name": "Ada"}
print(person["age"])person = {"name": "Ada"}
print(person.get("age", "Not specified"))- Use
.get(key, default)whenever a key might not exist. - Use
into check for a key before assuming it's there:if "age" in person:. - Prefer dictionaries over parallel lists when values are naturally related, like a name and its age.
- Use
.items()when you need both key and value in a loop.
Exercise & Challenge
Exercise 1 — Fill in the blank
stock = {"pencil": 12}
count = ____________________Complete the line so that stock["pen"] safely returns 0 if "pen" isn't already a key, instead of crashing.
🏆 Challenge
Build a simple contact book: a dictionary mapping names to phone numbers. Add three contacts, then look one up with get(), providing 'Not found' as a fallback for a name that isn't in the book.
- Store at least 3 name→phone pairs
- Use .get() for the lookup
- Print the result of both a successful and an unsuccessful lookup
💡 Need a hint?
contacts = {"Ada": "555-0100"}
🔍 Show a sample solution
contacts = {"Ada": "555-0100", "Sam": "555-0142", "Lee": "555-0199"}
print(contacts.get("Sam", "Not found"))
print(contacts.get("Max", "Not found"))Quiz
Answer every question, then submit to see your score and explanations.
1. How do you safely look up a key that might not exist?
2. What does .items() give you in a for loop?
3. What happens if you assign to a key that already exists?
4. What error does person["age"] raise if "age" isn't a key?
Summary
- Dictionaries store key → value pairs, looked up by key rather than position.
- Square-bracket access crashes on a missing key; .get(key, default) does not.
- Assigning to an existing key updates it; assigning to a new key adds it.
- .items() lets you loop through keys and values together.