What If You Want to Look Something Up by Name?
In the last chapter, you learnt how lists let you store collections of data. Lists are brilliant when you want to keep things in order and access them by position — item 0, item 1, item 2, and so on. But what if you want to look something up by name instead of by number? That’s where dictionaries come in.
Think about a real dictionary: you look up a word (the key) to find its definition (the value). You don’t need to know that “aardvark” is the first entry or that “zebra” is near the end — you just go straight to the word you want. Python dictionaries work the same way: every piece of data has a key that you use to find its value.
You see this pattern everywhere in real life:
- Phone contacts: you look up a person’s name (key) to find their phone number (value)
- Student records: a student’s name (key) paired with their grade (value)
- Product prices: a product name (key) paired with its price (value)
- Country capitals: a country name (key) paired with its capital city (value)
By the end of this chapter, you will be able to:
- Create dictionaries that pair keys with values
- Access values by their key
- Add, update, and delete items in a dictionary
- Loop through dictionaries to process all their data
- Work with nested dictionaries and lists inside dictionaries
- Build dictionaries dynamically using loops
- Understand how dictionaries relate to GCSE “records” and real-world data formats like JSON
See It in Action
Example 1: Creating and Accessing a Dictionary
Let’s create a dictionary that stores information about a student. Each piece of information has a key (like "name") and a value (like "Alice"). We use curly braces {} to define a dictionary and colons : to separate each key from its value.
# Create a dictionary for a student
student = {"name": "Alice", "age": 15, "year": 10}
# Print the whole dictionary
print(student)
# Access individual values by their key
print(student["name"])
print(student["age"])
print(student["year"])
Notice how we use square brackets with the key name inside — student["name"] — to get the value we want. This is different from lists, where you use a number index like my_list[0]. With dictionaries, you go directly to the data you need by name.
"favourite_subject": "Computer Science". Can you print just the favourite subject? Try changing Alice’s age to 16 and run the code again.
Example 2: Modifying a Dictionary
Dictionaries are mutable — you can change them after they’ve been created. You can add new key-value pairs, update existing values, and delete entries you no longer need.
# Start with a basic student dictionary
student = {"name": "Alice", "age": 15, "year": 10}
print("Original:", student)
# Add a new key-value pair
student["house"] = "Maple"
print("After adding house:", student)
# Update an existing value
student["age"] = 16
print("After birthday:", student)
# Delete a key-value pair
del student["year"]
print("After removing year:", student)
Adding and updating use exactly the same syntax: dictionary[key] = value. If the key already exists, the value is replaced. If the key is new, it gets added. The del keyword removes a key and its value entirely.
"email" with any email address as the value. Then update the student’s name to "Alice Smith". What happens if you try to delete a key that doesn’t exist, like del student["height"]?
Example 3: Looping Through a Dictionary
Just like lists, you can loop through dictionaries. The most useful approach is to loop through both the keys and the values at the same time using the .items() method.
# A dictionary of student information
student = {"name": "Alice", "age": 15, "year": 10, "house": "Maple"}
# Loop through all key-value pairs
print("--- Student Record ---")
for key, value in student.items():
print(f"{key}: {value}")
print()
# You can also loop through just the keys
print("Keys:", list(student.keys()))
# Or just the values
print("Values:", list(student.values()))
The .items() method gives you each key-value pair as a tuple, which we unpack into two variables: key and value. You can name these variables anything you like — k, v or field, data would work just as well — but clear names make your code easier to read.
{"Ravi": "blue", "Fatima": "green"}) and use a loop to print a sentence for each one, like "Ravi's favourite colour is blue.". Can you count how many entries are in the dictionary using len()?
Example 4: Nested Dictionaries
A dictionary can contain other dictionaries as its values. This is called nesting, and it is incredibly useful for organising complex, structured data — like a school database where each year group has its own set of details.
# A dictionary of dictionaries — each year group has student details
school = {
"Year10": {"name": "Alice", "age": 15, "form": "10B"},
"Year11": {"name": "Bob", "age": 16, "form": "11A"},
"Year12": {"name": "Charlie", "age": 17, "form": "12C"}
}
# Access the whole Year10 dictionary
print("Year 10 record:", school["Year10"])
# Access a specific value inside a nested dictionary
print("Year 11 student:", school["Year11"]["name"])
print("Year 12 form group:", school["Year12"]["form"])
# Loop through all year groups
print("\n--- All Students ---")
for year, details in school.items():
print(f"{year}: {details['name']} (Age {details['age']}, Form {details['form']})")
To access data inside a nested dictionary, you chain square brackets: school["Year11"]["name"] first looks up the "Year11" key (which gives you a dictionary), then looks up "name" inside that dictionary. Think of it as opening one box to find another box inside.
"Year13" entry with your own name, age, and form group. Can you update Bob’s age to 17? Try printing just the names of all students using a loop.
Example 5: Dictionary with List Values
Dictionary values don’t have to be single items — they can be lists. This is perfect when you need to store multiple values for a single key, such as a student’s test scores across several assessments.
# Each subject maps to a list of test scores
subjects = {
"Maths": [85, 90, 78],
"English": [72, 88, 91],
"Science": [95, 82, 88]
}
# Access all Maths scores
print("Maths scores:", subjects["Maths"])
# Access a specific score (first English test)
print("First English test:", subjects["English"][0])
# Add a new score to Science
subjects["Science"].append(90)
print("Updated Science scores:", subjects["Science"])
# Calculate averages for each subject
print("\n--- Subject Averages ---")
for subject, scores in subjects.items():
average = sum(scores) / len(scores)
print(f"{subject}: {average:.1f}%")
Because the values are lists, you can use all the list operations you already know — .append(), indexing with [0], len(), sum(), and so on. The combination of dictionaries and lists is one of the most powerful patterns in Python.
"Computing" with three test scores of your choice. Can you find which subject has the highest average? Try using max() on the averages.
Example 6: Building a Dictionary with a Loop
You don’t always have to type out every key-value pair by hand. You can build a dictionary dynamically using a loop — this is essential when working with data from files, user input, or calculations.
# Build a dictionary of squares using a loop
squares = {}
for number in range(1, 11):
squares[number] = number ** 2
print("Squares:", squares)
print("7 squared is:", squares[7])
# Build a dictionary from two lists using zip()
names = ["Alice", "Bob", "Charlie", "Diana"]
scores = [85, 92, 78, 95]
student_scores = {}
for name, score in zip(names, scores):
student_scores[name] = score
print("\nStudent Scores:", student_scores)
# Find the top student
top_student = max(student_scores, key=student_scores.get)
print(f"Top student: {top_student} with {student_scores[top_student]}%")
The pattern is simple: start with an empty dictionary {}, then inside a loop, assign values using dictionary[key] = value. The zip() function is particularly handy — it pairs up items from two lists so you can loop through them together.
"hello" to how many times it appears. (Hint: loop through the letters and use .get() to handle letters you haven’t seen yet.) Can you extend it to work with any word the user types?
How Does It Work?
Dictionary Syntax
A dictionary is defined using curly braces {}. Inside the braces, you write key-value pairs separated by commas. Each pair uses a colon : to connect the key to its value:
# The general pattern:
# my_dict = {key1: value1, key2: value2, key3: value3}
# A real example
capitals = {
"France": "Paris",
"Japan": "Tokyo",
"Brazil": "Brasilia",
"United Kingdom": "London"
}
print(capitals["United Kingdom"])
print(f"There are {len(capitals)} countries in the dictionary.")
Rules for Keys and Values
There are a few important rules to remember:
- Keys must be unique. If you use the same key twice, the second value overwrites the first.
- Keys must be immutable (they cannot be changed). This means you can use strings, numbers, or tuples as keys — but not lists.
- Values can be anything — strings, numbers, lists, other dictionaries, or even a mix of different types.
Useful Dictionary Methods
Python gives you several handy methods for working with dictionaries:
| Method | What It Does | Example |
|---|---|---|
.keys() |
Returns all the keys | student.keys() |
.values() |
Returns all the values | student.values() |
.items() |
Returns all key-value pairs | student.items() |
.get(key, default) |
Returns the value for a key, or a default if the key is missing | student.get("name", "Unknown") |
key in dict |
Checks whether a key exists | "name" in student |
del dict[key] |
Removes a key-value pair | del student["age"] |
len(dict) |
Returns the number of key-value pairs | len(student) |
.get() to Avoid Errors
If you try to access a key that doesn’t exist using square brackets — like student["height"] — Python will crash with a KeyError. The safer approach is to use .get("height", "Not recorded"), which returns a default value instead of crashing. This is especially important when you’re working with data that might be incomplete.
Dictionaries vs Lists
When should you use a dictionary instead of a list? Here is a simple guide:
- Use a list when you have a collection of similar items and the order matters (e.g. a list of scores, a queue of names).
- Use a dictionary when each item has a label or name and you want to look things up by that label (e.g. a student’s details, a set of configuration settings).
Records (GCSE Terminology)
In GCSE Computer Science exams, you will often see the term record. A record is a collection of related fields — for example, a single student’s name, age, and year group together form one record. In Python, a dictionary is the natural way to represent a record, because each field has a name (the key) and a value.
A list of dictionaries can represent a whole database table, where each dictionary is one record:
# A list of records (like a database table)
students = [
{"name": "Alice", "age": 15, "year": 10, "grade": "A"},
{"name": "Bob", "age": 16, "year": 11, "grade": "B"},
{"name": "Charlie", "age": 15, "year": 10, "grade": "A*"},
{"name": "Diana", "age": 16, "year": 11, "grade": "C"}
]
# Print all records
print("--- Student Database ---")
for student in students:
print(f"{student['name']}, Year {student['year']}: Grade {student['grade']}")
# Search for a specific record
print("\n--- Search: Year 10 Students ---")
for student in students:
if student["year"] == 10:
print(f" {student['name']} (Grade {student['grade']})")
Common Mistakes
student["height"] and the key "height" does not exist, Python will crash with a KeyError. Always use .get("height", default_value) or check with if "height" in student: first. This is the single most common dictionary error.
{} (empty dict) with set(): Don’t confuse curly braces for dictionaries {"key": "value"} with curly braces for sets {1, 2, 3}. If there are colons inside, it’s a dictionary. If there are just values with no colons, it’s a set. An empty pair of curly braces {} creates an empty dictionary, not an empty set. To create an empty set, you must write set().
my_dict[[1, 2]] = "value" — Python will raise a TypeError: unhashable type: 'list'. Use a tuple instead: my_dict[(1, 2)] = "value".
{"a": 1, "a": 2} results in {"a": 2} — the first value is lost without any error message. Always make sure your keys are unique.
import json; data = json.loads(json_string). If you understand dictionaries, you already understand the structure of most data on the web.
Where Are Dictionaries Used in the Real World?
Dictionaries are not just a classroom concept — they are used everywhere in professional software development. Here are some of the most important real-world applications:
{"city": "London", "temperature": 14, "condition": "Cloudy", "humidity": 72}
Python can read this directly into a dictionary, making it easy to extract the data you need.
{"health": 100, "attack": 25, "defence": 15, "speed": 30, "level": 5}
When the character levels up, the game updates the values. When the character takes damage, the
"health" value is reduced. Dictionaries make it easy to manage complex game state.
{"theme": "dark", "font_size": 14, "auto_save": True, "language": "en-GB"}
When you change a setting, the application updates the corresponding value and saves it to a file.
{"hello": "bonjour", "goodbye": "au revoir", "please": "s'il vous plaît", "thank you": "merci"}
The user types a word (the key), and the app looks up the translation (the value). This is dictionary lookup in its most literal form.
Key Vocabulary
Make sure you understand each of these terms. They will appear in lessons, homework, and exam questions.
| Term | Definition |
|---|---|
| Dictionary | A Python data structure that stores data as key-value pairs, enclosed in curly braces {}. |
| Key | The unique identifier used to look up a value in a dictionary. Keys must be immutable (e.g. strings, numbers, tuples). |
| Value | The data associated with a key. Values can be any data type, including lists, other dictionaries, or a mix. |
| Key-Value Pair | A single entry in a dictionary, written as key: value. For example, "name": "Alice". |
| Mutable | Something that can be changed after it is created. Dictionaries are mutable — you can add, update, and delete entries. |
| Hash Table | The internal data structure Python uses to implement dictionaries. It allows near-instant lookups regardless of dictionary size. |
| Mapping | The concept of associating one value (a key) with another value. A dictionary is Python’s built-in mapping type. |
.get() |
A dictionary method that safely retrieves a value by key, returning a default value if the key does not exist (instead of raising a KeyError). |
.keys() |
A dictionary method that returns all the keys in the dictionary. |
.values() |
A dictionary method that returns all the values in the dictionary. |
.items() |
A dictionary method that returns all key-value pairs as tuples, commonly used in for loops. |
del |
A Python keyword used to delete a key-value pair from a dictionary, e.g. del my_dict["key"]. |
| Nested Dictionary | A dictionary that contains other dictionaries as values, allowing multi-level data structures. |
| JSON | JavaScript Object Notation — a text-based data format used across the internet that is structurally similar to a Python dictionary. |
Worked Example: Building a Student Gradebook
The Problem
A teacher wants to track test scores for their class. For each student, they need to store multiple test scores, calculate each student’s average, find the student with the highest average, and display a formatted report. Let’s build this step by step.
Step 1: Create the Gradebook
We create a dictionary where each key is a student’s name and each value is a list of their test scores.
Step 2: Calculate Averages
We loop through the dictionary and calculate the average for each student using sum() and len().
Step 3: Find the Top Student
We track the highest average as we loop, storing the name of the best-performing student.
Step 4: Display the Report
We format the output neatly so the teacher can read it at a glance.
Complete Solution
# Step 1: Create the gradebook
gradebook = {
"Alice": [85, 92, 78, 95],
"Bob": [72, 68, 80, 75],
"Charlie": [90, 95, 88, 92],
"Diana": [65, 70, 72, 68],
"Ethan": [88, 84, 90, 86]
}
# Step 2 & 3: Calculate averages and find the top student
print("=" * 40)
print(" STUDENT GRADEBOOK REPORT")
print("=" * 40)
print(f"{'Student':<12} {'Scores':<20} {'Average':>7}")
print("-" * 40)
top_student = ""
top_average = 0
for student, scores in gradebook.items():
average = sum(scores) / len(scores)
scores_str = ", ".join(str(s) for s in scores)
print(f"{student:<12} {scores_str:<20} {average:>7.1f}%")
# Track the highest average
if average > top_average:
top_average = average
top_student = student
# Step 4: Display summary
print("-" * 40)
print(f"\nTotal students: {len(gradebook)}")
print(f"Top student: {top_student} with an average of {top_average:.1f}%")
# Calculate class average
all_averages = []
for scores in gradebook.values():
all_averages.append(sum(scores) / len(scores))
class_average = sum(all_averages) / len(all_averages)
print(f"Class average: {class_average:.1f}%")
Your Turn
Create a dictionary that stores information about a pet — its name, species, and age. Then print each detail on its own line using the keys to access the values.
STEP 2: Print the pet’s name by accessing pet["name"]
STEP 3: Print the pet’s species by accessing pet["species"]
STEP 4: Print the pet’s age by accessing pet["age"]
# Create a dictionary for your pet
pet = {"name": "____", "species": "____", "age": ____}
# Print each detail
print(f"Name: {pet['____']}")
print(f"Species: {pet['____']}")
print(f"Age: {pet['____']}")
pet = {"name": "Buddy", "species": "dog", "age": 4}. Then in the print statements, use the matching key names: pet["name"], pet["species"], and pet["age"]. Remember that the age should be a number (no quotation marks), but the name and species are strings (with quotation marks).Create a simple phone book using a dictionary. Start with two contacts, then add a third. Finally, look up one of the contacts and print their number.
STEP 2: Print the phone book
STEP 3: Add a third contact using phone_book[name] = number
STEP 4: Print the updated phone book
STEP 5: Look up a specific contact and print their number
# Create a phone book with two contacts
phone_book = {
"____": "____",
"____": "____"
}
print("Phone book:", phone_book)
# Add a third contact
# Print the updated phone book
# Look up a contact and print their number
Fill in the blanks with real names and phone numbers, like "Priya": "07700 123456". To add a third contact, write something like phone_book["Marcus"] = "07700 654321". To look up a contact, use print(f"Priya's number is {phone_book['Priya']}").
Bonus challenge: use .get() to look up someone who is not in the phone book and print a friendly message like "Contact not found" instead of crashing.
Create a program that stores a mini database of information — it could be film ratings, game scores, book reviews, recipe ingredients, or anything you like. Store at least four entries in a dictionary, then use a loop to display a nicely formatted summary.
STEP 2: Create a dictionary with at least four key-value pairs
STEP 3: Print a heading for your summary
STEP 4: Loop through the dictionary and print each entry in a readable format
STEP 5: Add a summary statistic (e.g. total entries, average score, highest rating)
# Mini Database
# Choose a theme and create your dictionary here
# Display a formatted summary
Here is an example using film ratings to get you started:
film_ratings = {"Inception": 9, "Frozen": 7, "Interstellar": 10, "Shrek": 8}
Then loop through with:
for film, rating in film_ratings.items():
print(f"{film}: {rating}/10")
For a summary statistic, you could calculate the average: sum(film_ratings.values()) / len(film_ratings). Or find the highest-rated film using max(film_ratings, key=film_ratings.get).
Be creative — there is no single right answer. The goal is to practise creating dictionaries, looping through them, and presenting data clearly.
Given a sentence, count how many times each word appears using a dictionary. This is a classic programming problem and a brilliant example of building a dictionary dynamically.
STEP 2: Convert the sentence to lowercase (so "The" and "the" count as the same word)
STEP 3: Split the sentence into a list of individual words using .split()
STEP 4: Create an empty dictionary called word_counts
STEP 5: Loop through each word in the list
IF the word is already in the dictionary, add 1 to its count
ELSE add the word with a count of 1
STEP 6: Print each word and its count
# Word Frequency Counter
sentence = "the cat sat on the mat and the cat sat on the hat"
# Convert to lowercase and split into words
words = sentence.lower().split()
# Count each word
word_counts = {}
for word in words:
# Use .get() to handle words not yet in the dictionary
word_counts[word] = word_counts.get(word, 0) + 1
# Display the results
print("--- Word Frequencies ---")
for word, count in word_counts.items():
print(f" '{word}' appears {count} time(s)")
# Find the most common word
most_common = max(word_counts, key=word_counts.get)
print(f"\nMost common word: '{most_common}' ({word_counts[most_common]} times)")
The key technique here is word_counts.get(word, 0) + 1. The .get(word, 0) part returns the current count for that word, or 0 if the word hasn’t been seen yet. Then we add 1 and store it back.
Try it with your own sentence. What happens with punctuation? Can you strip out full stops and commas before counting? (Hint: try sentence.replace(".", "").replace(",", "") before splitting.)
Build a geography quiz using nested dictionaries. Store information about at least four countries (capital, population, continent), then create a quiz that asks the user questions and checks their answers.
STEP 2: Display all countries in the database
STEP 3: For each country, ask the user to name the capital
STEP 4: Check if the answer matches the stored capital
STEP 5: Keep a score and display the final result
# Country Quiz Database
countries = {
"France": {"capital": "Paris", "population": 67000000, "continent": "Europe"},
"Japan": {"capital": "Tokyo", "population": 125000000, "continent": "Asia"},
"Brazil": {"capital": "Brasilia", "population": 214000000, "continent": "South America"},
"Kenya": {"capital": "Nairobi", "population": 54000000, "continent": "Africa"},
"Australia": {"capital": "Canberra", "population": 26000000, "continent": "Oceania"}
}
# Display all countries
print("=== Country Database ===")
for country, info in countries.items():
pop_millions = info['population'] / 1000000
print(f"{country} ({info['continent']}): Capital = {info['capital']}, Pop = {pop_millions:.0f}M")
# Quiz section (without input - using a pre-set answer list for demo)
print("\n=== Capital City Quiz ===")
# Try changing these answers to test different results!
test_answers = ["Paris", "Tokyo", "Rio", "Nairobi", "Sydney"]
score = 0
for i, (country, info) in enumerate(countries.items()):
answer = test_answers[i]
correct = info["capital"]
if answer.lower() == correct.lower():
print(f" {country}: '{answer}' - Correct!")
score += 1
else:
print(f" {country}: '{answer}' - Wrong! The answer is {correct}.")
print(f"\nYour score: {score}/{len(countries)}")
The quiz uses nested dictionaries: countries["France"]["capital"] gives you "Paris". To make the quiz interactive, you would normally use input() to ask the user for answers. In this demo, we use a pre-set list of answers so you can see how the checking logic works.
Challenge: Add more countries. Can you add a second round that asks about continents instead of capitals? Can you randomise the order of questions?
Chapter Summary
What You Have Learnt
- Dictionaries store data as key-value pairs using curly braces
{}and colons:. - You access values by their key using square brackets:
my_dict["key"]. - Use
.get(key, default)for safe access that avoidsKeyErrorcrashes. - Dictionaries are mutable: you can add, update, and delete entries after creation.
- The methods
.keys(),.values(), and.items()let you loop through dictionaries. - Nested dictionaries (dictionaries inside dictionaries) let you represent complex, structured data.
- Dictionary values can be lists, letting you store multiple values per key.
- You can build dictionaries dynamically using loops.
- In GCSE terms, a dictionary represents a record, and a list of dictionaries represents a database table.
- Dictionaries are the backbone of JSON, the most common data format on the web.
Exam-Style Questions
Practise answering these questions as you would in an exam. Try writing your answers on paper before looking at the hints.
Test Your Knowledge
Question 1: What is a key-value pair? Give an example. 2 marks
A key-value pair is a single entry in a dictionary where a unique key is associated with (mapped to) a value. (1 mark)
Example: In {"name": "Alice"}, the key is "name" and the value is "Alice". (1 mark)
Question 2: Explain one advantage of using a dictionary over a list for storing student records. 2 marks
A dictionary allows you to access data by a meaningful key name (such as "name" or "grade") rather than having to remember a numerical index position. (1 mark)
This makes the code more readable and less error-prone, because student["name"] is clearer and more self-documenting than student[0]. (1 mark)
Question 3: Write Python code to create a dictionary of 3 products with prices, then use a loop to display each product and its price. 4 marks
Creating the dictionary (2 marks):
products = {"Bread": 1.20, "Milk": 0.95, "Eggs": 2.50}
Looping and displaying (2 marks):
for product, price in products.items():
print(f"{product}: £{price:.2f}")
Award 1 mark for a correctly structured dictionary with 3 items, 1 mark for correct data types (strings for names, floats/numbers for prices), 1 mark for a correct for loop using .items(), and 1 mark for correct output using both variables.
# Write your answer to Question 3 here
Think About It
Take a moment to think about what you’ve learnt in this chapter. Try to answer these questions in your head or discuss them with a classmate:
- How is a dictionary different from a list? When would you choose one over the other?
- Why is it safer to use
.get()instead of square brackets when you’re not sure a key exists? - Can you think of three real-world examples where data is organised as key-value pairs?
- What happens if you try to add a key that already exists in a dictionary? Why might this be useful?
- Why must dictionary keys be immutable? What problems could arise if you were allowed to use a list as a key?
- How would you represent a school timetable using nested dictionaries? What would the keys and values be?
- Why are dictionaries so widely used in web development and APIs?
Connection to the Capstone
Dictionaries are one of the most powerful tools in Python. In the capstone project (Chapter 11), you will build a complete quiz game — and the quiz game will store its questions and answers in a dictionary. Each question (the key) will be paired with its correct answer (the value), making it easy to check whether the player got it right. You will also use nested dictionaries to store additional information like difficulty levels and categories.
External Resources
Explore more about dictionaries and data structures:
- BBC Bitesize Edexcel Computer Science — GCSE-level revision on data structures, algorithms, and programming concepts
- W3Schools Python Dictionaries — Interactive tutorials and reference for all dictionary methods
- GCSE Topic 6: Data Types & File Handling — Arrays, file processing, and authentication systems with interactive code editors
- File Processing Builder — Build file handling programs step by step
What’s Next?
You now know how to store and organise data using both lists and dictionaries. But so far, you haven’t done much with the text (strings) inside them. In Chapter 9: String Manipulation, you’ll learn how to slice, search, format, and transform text — skills that are essential for building real-world programs that work with names, messages, and user input.