Dictionaries
Prerequisites: Lists
A dictionary stores key/value pairs — instead of numbered positions like a list, each value has a named key.
Syntax
user = {"name": "Ada", "age": 25}
Example
print(user["name"])
user["age"] = 26
for key, value in user.items():
print(key, value)
Expected output
Ada
name Ada
age 26
.items() gives both the key and value together, ready to loop over.
Common mistakes
- Accessing a key that doesn't exist raises
KeyError. Useuser.get("email")instead, which returnsNonerather than crashing if the key is missing.
Practice
Create a dictionary representing a book with title and author keys,
then print "{title} by {author}".
Show solution
book = {"title": "Dune", "author": "Frank Herbert"}
print(f"{book['title']} by {book['author']}")