← Back to Python Course | Chapter 6: Data Structures | Lesson 10 of 12

Python Nested Data Structures

List of Lists

A list of lists is Python's standard way to represent a 2D grid or matrix, where the outer list holds rows and each inner list holds that row's columns -- grid[row][column] reads the element at that position, first indexing into the outer list, then the inner one.

Example: List of Lists

python
grid = [[1, 2], [3, 4]]
print(grid[1][0])

Dictionary of Dictionaries

Nesting dictionaries inside a dictionary lets you group related records under a single parent key, like users[alice] = {age: 30, email: '...'} -- this mirrors how JSON APIs commonly structure profile or configuration data.

Example: Dictionary of Dictionaries

python
users = {"alice": {"age": 30, "email": "[email protected]"}}
print(users["alice"]["age"])

List of Dictionaries

A list of dictionaries -- [{id: 1, name: A}, {id: 2, name: B}] -- is exactly the shape most database query results and JSON API responses take, with each dict representing one row or record and the list representing the full result set.

Example: List of Dictionaries

python
records = [{"id": 1, "name": "A"}, {"id": 2, "name": "B"}]
print(records[1]["name"])

Dictionary of Lists

Mapping a single key to a list of values (a dict of lists) is the natural structure for grouping data by category, such as tags_to_articles[python] = [article1, article2] holding every article tagged python under one key.

Example: Dictionary of Lists

python
tags_to_articles = {"python": ["article1", "article2"]}
print(tags_to_articles["python"])

Iterating through Nested Data

Walking nested structures usually means one loop per level of nesting -- a for loop over the outer list, with a nested for loop (or dict iteration) inside it -- and getting the loop variable names right at each level is what keeps the code readable.

Example: Iterating through Nested Data

python
grid = [[1, 2], [3, 4]]
for row in grid:
    for value in row:
        print(value)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.