Dictionaries
Learn how to store and look up information using key-value pairs — Python's most powerful built-in data structure.
Imagine a real dictionary. You look up a word (the key) and find its definition (the value). Python dictionaries work exactly the same way — you store pairs of information, and you can instantly look up any value by its key.
This makes dictionaries perfect for things like storing a person's name and age together, mapping country codes to country names, or tracking scores in a game.
See it in action
— step through the idea, then dive into the details below.Data with Labels, Not Positions
A dictionary stores information as key: value pairs. Instead of remembering position 0, you look things up by a meaningful name — just like a real dictionary.
#Creating a Dictionary
You create a dictionary with curly braces {}. Inside, you write key: value pairs, separated by commas. Keys and values can be almost any type — strings, numbers, even other dictionaries.
# A dictionary storing a person's details
person = {
"name": "Amara",
"age": 28,
"city": "Lagos"
}
print(person)Think of it like a contact card
A contact card has labels like Name, Phone, and Email — those are the keys. The actual name and number written in are the values. A dictionary is just a digital contact card.
#Accessing Values
To get a value out of a dictionary, use square brackets with the key inside: d[key]. This is called indexing. If the key does not exist, Python raises a KeyError.
person = {"name": "Amara", "age": 28, "city": "Lagos"}
print(person["name"])
print(person["age"])KeyError: the key does not exist
If you try person["email"] and "email" is not in the dictionary, Python crashes with a KeyError. Always make sure the key exists before accessing it — or use .get() instead (covered next).
#Safe Lookups with .get()
The .get(key, default) method is a safer way to look up a value. If the key does not exist, it returns the default value you provide instead of crashing. If you leave out the default, it returns None.
person = {"name": "Amara", "age": 28}
# Key exists — returns the value
print(person.get("name", "Unknown"))
# Key missing — returns the default
print(person.get("email", "No email on file"))#Adding and Updating Entries
You can add a new key-value pair or update an existing one by assigning to d[key]. If the key already exists, the value is overwritten. If it does not exist, a new entry is created.
scores = {"Alice": 90, "Bob": 75}
# Add a new entry
scores["Charlie"] = 88
# Update an existing entry
scores["Bob"] = 82
print(scores)#Removing Entries with del
Use del d[key] to permanently remove a key-value pair from the dictionary.
scores = {"Alice": 90, "Bob": 82, "Charlie": 88}
del scores["Bob"]
print(scores)#Checking if a Key Exists
Use the in keyword to check whether a key exists in a dictionary before accessing it. This is a clean and fast way to avoid KeyError.
inventory = {"apples": 10, "bananas": 5}
if "apples" in inventory:
print("We have apples!")
if "grapes" not in inventory:
print("No grapes in stock.")#Iterating Over a Dictionary
You can loop over a dictionary in three useful ways: - .keys() — gives you all the keys - .values() — gives you all the values - .items() — gives you both, as (key, value) pairs
The .items() method is the most commonly used because you usually need both pieces.
prices = {"coffee": 3.50, "tea": 2.00, "juice": 4.25}
for item, price in prices.items():
print(f"{item} costs ${price:.2f}")Keys must be immutable and unique
Dictionary keys must be immutable — meaning they cannot change. Strings, numbers, and tuples make valid keys. Lists do not (they can change, so Python refuses them as keys).
Also, every key must be unique. If you add the same key twice, the second value quietly replaces the first.
#Nested Dictionaries
A dictionary value can itself be another dictionary. This lets you represent more complex, structured data — like a database record or a settings file.
students = {
"Alice": {"grade": "A", "age": 20},
"Bob": {"grade": "B", "age": 22}
}
# Access nested data with two sets of brackets
print(students["Alice"]["grade"])
print(students["Bob"]["age"])#Dict Comprehension (a quick peek)
Just like list comprehensions, you can build a dictionary in one line using a dict comprehension. The pattern is {key: value for item in iterable}. Do not worry if this looks complex — it will click with practice.
# Square each number and store it in a dict
squares = {n: n**2 for n in range(1, 6)}
print(squares)What does person.get("phone", "N/A") return if "phone" is not a key in the person dictionary?
Key takeaways
- Dictionaries store **key-value pairs** — look up any value instantly by its key.
- Use `d[key]` to access a value; use `.get(key, default)` to avoid a `KeyError` when the key might be missing.
- Add or update entries with `d[key] = value`; remove them with `del d[key]`.
- Loop over a dictionary with `.keys()`, `.values()`, or `.items()` — `.items()` gives you both at once.
- Keys must be **immutable** (strings, numbers, tuples) and **unique** within the dictionary.
What does this code print?
scores = {"Alice": 90, "Bob": 75}
scores["Bob"] = 82
scores["Charlie"] = 88
print(scores["Bob"])This code should print the city from the dictionary, but it crashes. What is wrong?
person = {"name": "Amara", "age": 28, "city": "Lagos"}
print(person["location"])Complete the code so it safely prints a person's email, showing "No email" if the key is missing.
person = {"name": "Amara", "age": 28} print(person.("email", "No email"))
Put these lines in the right order to build a dictionary, add an entry, and print all items.
inventory = {"apples": 10, "bananas": 5}print(item, count)
for item, count in inventory.items():
inventory["grapes"] = 8
Create a dictionary called phonebook that stores at least three people's names as keys and their phone numbers as strings. Then: 1. Print the phone number for one person using their name. 2. Add a new person to the phonebook. 3. Use a for loop with .items() to print every name and number in the format: "Name: <name>, Number: <number>".
Try it live — edit the code and hit Run to execute real Python: