We are thrilled to inform you that Lancecourse is NOW INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for INITAcademy.org.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

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!

  1. Create a dictionary named musician, with:
    • "name" (string)
    • "instruments" (list of instruments they play)
  2. Print each instrument they play using a loop.