Dictionaries¶
By the end of this lesson you'll be able to:
- Create a dictionary and access values by key
- Safely retrieve values with
get()to avoidKeyError - Add, update, and remove entries, and iterate over keys, values, and items
- Use nested dictionaries and dictionary comprehensions
A dictionary maps keys to values — exactly like a real-world dictionary maps words to definitions. Dictionaries are one of the most widely-used data structures in Python.
Welcome to Chapter 21!
Imagine a phone book that you can look up in any order, add new contacts to, and search in an instant.
That's a Python dictionary! Let's build one. Let's code it together!
Creating a Dictionary¶
A dictionary is created with curly braces {}. Each entry is a key: value pair, separated by commas.
1 2 3 4 5 | |
Keys must be unique within a dictionary. Keys are usually strings or numbers. Values can be anything — strings, numbers, lists, even other dictionaries.
Accessing Values by Key¶
Use square brackets with the key to retrieve a value:
1 | |
If the key doesn't exist, Python raises a KeyError — so be careful.
What Do You Think Will Happen?
The code below tries to access both a key that exists and one that doesn't.
What do you think happens when a key is missing? Make your guess — then run it!
Safe Access with get()¶
dict.get(key) returns the value if the key exists, or None if it doesn't — no crash.
You can also provide a default value: dict.get(key, default).
1 2 3 4 | |
Use get() whenever you're not sure whether a key exists.
See It: A Cabinet of Labeled Drawers¶
A dictionary works like a cabinet where every drawer has its key written on the front — Python jumps straight to the right drawer without opening the others. Before you try the lookup below, predict: what happens if you type Grace with a capital G instead of grace?
Explore the Dictionary Key Lookup MicroSim
Try a missing key both ways: with square brackets you get the KeyError crash, and with the .get() checkbox you get a polite None. Then check compare with a list search — the list has to check drawer after drawer, while the dictionary always takes one hop. That difference is why phone books, glossaries, and game inventories all use dictionaries.
Adding and Updating Entries¶
Add a new key or update an existing one using the same assignment syntax:
1 2 | |
Removing Entries¶
d.pop(key)— removes the key and returns its value (raisesKeyErrorif missing unless you pass a default)del d[key]— removes the key (raisesKeyErrorif missing)
1 2 | |
Keys, Values, and Items¶
Three dictionary methods give you different views of the data:
d.keys()— all keysd.values()— all valuesd.items()— all(key, value)pairs as tuples
Iterating over a Dictionary¶
You can loop over keys, values, or key-value pairs:
1 2 3 4 5 6 7 | |
Key Membership with in¶
Use in to check whether a key exists without causing a KeyError:
1 2 | |
Nested Dictionaries¶
A dictionary can contain other dictionaries as values. This is perfect for representing structured data — like a contacts list where each contact has several fields.
1 2 3 4 5 6 7 | |
Dictionary Comprehensions¶
A dictionary comprehension builds a new dictionary from an existing sequence, similar to a list comprehension.
Syntax: {key_expr: value_expr for item in iterable}
Before the comprehension, here's the long-form equivalent to make the pattern clear:
1 2 3 4 5 6 7 | |
The Default Dictionary Pattern¶
A common pattern is building a dictionary where missing keys should start with a default value.
The manual approach uses get():
1 2 3 | |
Learning Check¶
Your Turn — Build a Grade Book
The code below creates an empty grade book.
Add three students — "Alice" with 95, "Bob" with 87, and "Carol" with 91 —
then print each student's name and grade using a for loop over .items().
Experiments¶
Try these changes. Predict what will happen first, then run it to check!
-
Create a dictionary of capital cities:
{"France": "Paris", "Japan": "Tokyo", "Brazil": "Brasília"}. Print the capital of Japan. You'll know it worked when you seeTokyo. -
Add a new country to your capitals dictionary and print all keys. You'll know it worked when the new country appears in the key list.
-
Use a dictionary comprehension to create
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}(cubes of 1–5). You'll know it worked when you see those five key-value pairs. -
Try
capitals.get("Germany", "Unknown")when "Germany" isn't in the dictionary. You'll know it worked when you see "Unknown" instead of aKeyError. -
Count the frequency of each letter in
"mississippi"using the default dictionary pattern. You'll know it worked when you see{"m": 1, "i": 4, "s": 4, "p": 2}.
Dictionary Wizard!
You've mastered one of Python's most powerful data structures!
Dictionaries are everywhere — in APIs, configuration files, databases, and machine learning models.
Next chapter we'll combine all four collection types with Python's powerful built-in functions!