Working with dictionaries¶
In this tutorial, you will learn how to create, modify, and iterate over dictionaries — Python's key-value data structure.
Time commitment: 15–20 minutes
Prerequisites:
- Python 3.12 or later installed on your machine
- Completion of Working with lists and Working with tuples
Learning objectives¶
By the end of this tutorial, you will be able to:
- Create dictionaries and access values by key
- Add, update, and remove entries
- Iterate over keys, values, and items
- Work with nested dictionaries
What is a dictionary?¶
A dictionary is a mutable collection of key-value pairs. Each key maps to a value, allowing fast lookups by key. Since Python 3.7, dictionaries preserve the order in which items are inserted.
Dictionaries are created using curly braces {}:
person = {"name": "Alice", "age": 30, "city": "London"}
print(person)
You can also create a dictionary using the dict() constructor:
person = dict(name="Alice", age=30, city="London")
print(person)
Accessing values by key¶
Use square brackets with the key to retrieve a value:
person = {"name": "Alice", "age": 30, "city": "London"}
print(person["name"])
print(person["city"])
If the key does not exist, Python raises a KeyError. To avoid this, use the get() method, which returns None (or a default value you specify) when the key is missing:
person = {"name": "Alice", "age": 30}
print(person.get("name")) # "Alice"
print(person.get("email")) # None
print(person.get("email", "N/A")) # "N/A" (default value)
Adding and updating entries¶
To add a new entry or update an existing one, assign a value using square brackets:
person = {"name": "Alice", "age": 30}
# Add a new entry
person["email"] = "alice@example.com"
print(person)
# Update an existing entry
person["age"] = 31
print(person)
You can also use update() to merge in values from another dictionary:
person = {"name": "Alice", "age": 30}
person.update({"age": 31, "city": "Manchester"})
print(person)
Removing entries¶
Use del to remove an entry by key:
person = {"name": "Alice", "age": 30, "city": "London"}
del person["city"]
print(person)
Use pop() to remove an entry and get its value back:
person = {"name": "Alice", "age": 30, "city": "London"}
city = person.pop("city")
print(f"Removed: {city}")
print(f"Remaining: {person}")
You can provide a default value to pop() to avoid a KeyError if the key does not exist:
person = {"name": "Alice"}
email = person.pop("email", "not found")
print(email)
Iterating over a dictionary¶
By default, iterating over a dictionary gives you its keys:
person = {"name": "Alice", "age": 30, "city": "London"}
for key in person:
print(key)
Use values() to iterate over the values:
for value in person.values():
print(value)
Use items() to iterate over both keys and values together:
for key, value in person.items():
print(f"{key}: {value}")
Checking membership¶
The in keyword checks whether a key exists in the dictionary:
person = {"name": "Alice", "age": 30}
print("name" in person) # True
print("email" in person) # False
To check whether a value exists, use in with values():
print(30 in person.values()) # True
Nested dictionaries¶
Dictionary values can themselves be dictionaries, allowing you to represent structured, hierarchical data:
school = {
"Alice": {"age": 15, "subjects": ["Maths", "Science"]},
"Bob": {"age": 16, "subjects": ["English", "History"]},
}
print(school["Alice"]["subjects"])
print(school["Bob"]["age"])
You can iterate over nested dictionaries using nested loops:
for name, details in school.items():
subjects = ", ".join(details["subjects"])
print(f"{name} (age {details['age']}): {subjects}")
Exercise: build a contact book¶
Create a dictionary called contacts that stores three people. For each person, store their phone number and email address as a nested dictionary. Then:
- Print one contact's email address
- Add a new contact
- Print all contact names and their phone numbers
# Write your code here
Solution¶
Here is one way to complete the exercise:
contacts = {
"Alice": {"phone": "07700 900001", "email": "alice@example.com"},
"Bob": {"phone": "07700 900002", "email": "bob@example.com"},
"Charlie": {"phone": "07700 900003", "email": "charlie@example.com"},
}
# 1. Print one contact's email
print(f"Alice's email: {contacts['Alice']['email']}")
# 2. Add a new contact
contacts["Diana"] = {"phone": "07700 900004", "email": "diana@example.com"}
# 3. Print all names and phone numbers
for name, details in contacts.items():
print(f"{name}: {details['phone']}")
Summary¶
In this tutorial, you learned how to:
- Create dictionaries using curly braces
{}anddict() - Access values by key and use
get()for safe access - Add, update, and remove entries
- Iterate over keys, values, and items
- Check for key membership with
in - Work with nested dictionaries
What is next¶
In the next tutorial, you will explore:
- Sets — unordered collections of unique items