Dictionaries and Lists
When you combine dictionaries and lists, you unlock powerful ways to organize and work with complex data!
List of Dictionaries
Sometimes, you want to manage a collection of similar items. You can store multiple dictionaries inside a list:
students = [
{"name": "Ama", "age": 20},
{"name": "Yaw", "age": 22},
{"name": "Kojo", "age": 19}
]
Each item in the list is a dictionary with details about a student.
Looping Through List of Dictionaries
You can loop through the list and access each dictionary:
for student in students:
print(f"{student['name']} is {student['age']} years old.")
Output
Ama is 20 years old.
Yaw is 22 years old.
Kojo is 19 years old.
Notice how we access values using the key names (student['name']
and student['age']
).
Modifying Dictionaries in a List
You can modify dictionaries while looping:
for student in students:
student["graduated"] = False
print(students)
Output
[
{'name': 'Ama', 'age': 20, 'graduated': False},
{'name': 'Yaw', 'age': 22, 'graduated': False},
{'name': 'Kojo', 'age': 19, 'graduated': False}
]
Adding New Dictionaries
You can add new entries to the list:
students.append({"name": "Afia", "age": 21})
Now your list has 4 students!
Exercise: Try It Yourself!
-
Create a list of dictionaries called books, each dictionary should have:
"title"
,"author"
,"year"
-
Loop through the list and print out each book's title and year.