Dictionaries
On this page
Creating DictionariesAccess ItemsChange ItemsAdd ItemsRemove ItemsLoop Through DictionariesCopy DictionariesNested DictionariesMini Project — Interactive Student GradebookA dictionary in Python is a collection that stores data in key–value pairs. Unlike lists or tuples, where elements are accessed by position, dictionaries let you access values by their associated keys. Use them to represent structured data such as user profiles, product catalogues, or database records.
Dictionaries preserve insertion order. They are mutable and dynamic: you can change their values and add or remove entries after creation.
Creating Dictionaries
Dictionaries are created using curly braces {} with each pair written as key: value.
student = {
"name": "Alice",
"age": 22,
"major": "Computer Science"
}
print(student)Output
{'name': 'Alice', 'age': 22, 'major': 'Computer Science'}
Access Items
You can access a dictionary value by using its key inside square brackets [] or with the safer .get() method.
print(student["name"])
print(student.get("age"))Output
Alice
22
If a key does not exist,student["grade"] would raise an error, while student.get("grade") would return None. This makes .get() safer for uncertain keys.
Change Items
Dictionaries are mutable, so you can update the value of an existing key easily.
student["age"] = 23
student["major"] = "Data Science"
print(student)Output
{'name': 'Alice', 'age': 23, 'major': 'Data Science'}
To update multiple fields at once, use the .update() method:
student.update({"age": 24, "year": "Final"})
print(student)Output
{'name': 'Alice', 'age': 24, 'major': 'Data Science', 'year': 'Final'}
Add Items
Adding a new key–value pair is as simple as assigning a new key:
student["GPA"] = 3.9
print(student)Output
{'name': 'Alice', 'age': 24, 'major': 'Data Science', 'year': 'Final', 'GPA': 3.9}
The .update() method can also be used to add multiple items at once.
Remove Items
You can remove dictionary items in several ways: by using pop() to remove a specific key,popitem() to remove the last inserted pair,del to delete a key entirely, or clear() to remove all items from the dictionary.
student.pop("year") # removes item by key
print(student)Output
{'name': 'Alice', 'age': 24, 'major': 'Data Science', 'GPA': 3.9}
student.popitem() # removes the last inserted key–value pair
print(student)Output
{'name': 'Alice', 'age': 24, 'major': 'Data Science'}
del student["age"] # removes key entirely
print(student)Output
{'name': 'Alice', 'major': 'Data Science'}
student.clear() # removes all items
print(student)Output
{}
Loop Through Dictionaries
This previews the for loop, developed in Control Flow: it takes one item at a time and runs the indented body for that item. values() supplies values, and items() supplies key–value pairs that can be unpacked into two names.
student = {"name": "Alice", "age": 24, "major": "Data Science"}
# Loop through keys
for key in student:
print(key)
# Loop through values
for value in student.values():
print(value)
# Loop through both keys and values
for key, value in student.items():
print(key, ":", value)Output
name
age
major
Alice
24
Data Science
name : Alice
age : 24
major : Data Science
This technique is useful for displaying structured data or processing user records.
Copy Dictionaries
Assigning one dictionary to another variable (b = a) doesn’t create a new copy—it creates a reference. Use .copy() or dict() for a shallow copy: the outer dictionary is new, but mutable values nested inside it are still shared.
student = {"name": "Alice", "age": 24}
copy_student = student.copy()
copy_student["name"] = "Eve"
print(student)
print(copy_student)Output
{'name': 'Alice', 'age': 24}
{'name': 'Eve', 'age': 24}
Nested Dictionaries
Dictionaries can also hold other dictionaries as values, allowing more complex structures. This is common when modeling related data.
students = {
"A1": {"name": "Alice", "age": 22},
"B2": {"name": "Bob", "age": 23},
"C3": {"name": "Charlie", "age": 21}
}
print(students["A1"]["name"])Output
Alice
You can loop through nested dictionaries to display all details:
for student_id, info in students.items():
print(student_id, "=>", info["name"], "-", info["age"])Output
A1 => Alice - 22
B2 => Bob - 23
C3 => Charlie - 21
Find more dictionary methods on the Python official documentation.
Mini Project — Interactive Student Gradebook
Write a program that manages a small student gradebook using Python dictionaries. The program should allow users to add students and their grades, update existing grades, and calculate the class average. Complete the interactive version after For Loops and Built-in Functions introduce repetition and sum(). For now, trace updates to the three sample records.
Example Run:
How many students are in the class? 3
Enter the name of student 1: Alice
Enter Alice's grade: 92
Enter the name of student 2: Bob
Enter Bob's grade: 85
Enter the name of student 3: Clara
Enter Clara's grade: 78
Current Gradebook:
Alice: 92.0
Bob: 85.0
Clara: 78.0
Would you like to update a student's grade? (yes/no): yes
Enter the student's name to update: Bob
Enter Bob's new grade: 88
Bob's grade has been updated.
Final Gradebook:
Alice: 92.0
Bob: 88.0
Clara: 78.0
Class average: 86.0