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

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!

  1. Create a list of dictionaries called books, each dictionary should have:

    • "title", "author", "year"
  2. Loop through the list and print out each book's title and year.