Lesson 25 of 4063%

(Progress persistence is disabled until Phase 9)

Python
Intermediate

Nested Data Structures

Lists inside dictionaries, dictionaries inside lists.

Nested Data Structures

What You’ll Learn

You’ll learn how to combine lists and dictionaries to build complex data structures, similar to JSON.

Dictionaries inside a List

This is a very common pattern when representing rows from a database or an API response.

users = [
    {"id": 1, "name": "Alice", "role": "Admin"},
    {"id": 2, "name": "Bob", "role": "User"},
    {"id": 3, "name": "Charlie", "role": "User"}
]

# Accessing Bob's role:
print(users[1]["role"]) # User

# Looping through all users:
for u in users:
    print(u["name"])

Lists inside a Dictionary

Useful for when a single entity has multiple items associated with it.

restaurant = {
    "name": "Pizza Planet",
    "menu": ["Pepperoni", "Margherita", "Hawaiian"],
    "rating": 4.5
}

# Accessing the second menu item:
print(restaurant["menu"][1]) # Margherita

Dictionaries inside Dictionaries

company = {
    "employee1": {"name": "John", "salary": 50000},
    "employee2": {"name": "Jane", "salary": 60000}
}

Lesson Progress

Practice This TopicTake QuizBuild a Python Project

Ready to practise?

Apply what you learned with a hands-on challenge.

Practise This Topic