Nested Data Structures
Introduction to Nested Data Structures
Nested data structures are collections that contain other collections. Lists can contain lists, dictionaries can contain dictionaries, and you can mix different types. This allows you to represent complex, hierarchical data.
Nested structures are common in real-world programming, such as representing JSON data, configuration files, or multi-dimensional data.
Nested Lists
Lists can contain other lists, creating multi-dimensional structures:
nested_lists.py
# 2D list (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Access elements
print(matrix[0][0]) # 1
print(matrix[1][2]) # 6
# Iterate through nested list
for row in matrix:
for element in row:
print(element, end=" ")
print()
Nested Dictionaries
Dictionaries can contain other dictionaries, creating hierarchical data structures:
nested_dicts.py
students = {
"student1": {
"name": "Alice",
"age": 20,
"grades": [85, 90, 88]
},
"student2": {
"name": "Bob",
"age": 21,
"grades": [92, 87, 95]
}
}
# Access nested data
print(students["student1"]["name"]) # Alice
print(students["student1"]["grades"][0]) # 85
# Iterate through nested dictionary
for student_id, info in students.items():
print(f"{student_id}: {info['name']}")
Mixed Structures
You can combine lists and dictionaries in various ways:
mixed.py
# List of dictionaries
people = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30}
]
# Dictionary with list values
classes = {
"math": ["Alice", "Bob", "Charlie"],
"science": ["Alice", "David"]
}
print(people[0]["name"]) # Alice
print(classes["math"][0]) # Alice
Accessing Nested Data
Use multiple indices or keys to access nested data:
accessing.py
data = {
"users": [
{"name": "Alice", "scores": [85, 90]},
{"name": "Bob", "scores": [92, 88]}
]
}
# Access nested data step by step
first_user = data["users"][0]
first_score = first_user["scores"][0]
print(first_score) # 85
# Or chain the access
print(data["users"][0]["scores"][0]) # 85
main.py
📤 Output
Click "Run" to execute...