Lists of Dictionaries
Sometimes, you want to build even more complex data structures by creating lists inside dictionaries or managing a full list of dictionary objects. This lesson shows you how!
A List Inside a Dictionary
You can store a list as a value in a dictionary:
student = {
"name": "Ama",
"courses": ["Math", "English", "Science"]
}
Here, "courses"
is a list attached to one key.
You can access the list and its elements like this:
print(student["courses"]) # Prints the list
print(student["courses"][0]) # Prints 'Math'
Looping Through Lists in Dictionaries
You can loop through the list inside the dictionary:
for course in student["courses"]:
print(f"{student['name']} is taking {course}")
Output
Ama is taking Math
Ama is taking English
Ama is taking Science
A List of Dictionaries
You can also create a list that contains multiple dictionaries:
books = [
{"title": "Python Basics", "author": "John"},
{"title": "Data Science 101", "author": "Jane"},
{"title": "AI Revolution", "author": "Sara"}
]
Now you have several book records managed together!
Looping Through a List of Dictionaries
You can easily loop through and access information:
for book in books:
print(f"{book['title']} by {book['author']}")
Output
Python Basics by John
Data Science 101 by Jane
AI Revolution by Sara
Exercise: Try It Yourself!
- Create a dictionary named musician, with:
"name"
(string)"instruments"
(list of instruments they play)
- Print each instrument they play using a loop.