![]()
A nested data structure is a data structure that contains other data structures within it. In Python, lists, tuples, dictionaries, and sets can be nested inside each other to store complex, hierarchical data.
Why Use Nested Data Structures?
Helps represent real-world hierarchical data
Improves organization and readability of data
Allows efficient data storage and retrieval
1. Types of Nested Data Structures
Python allows nesting different data structures inside each other. The most common combinations are:
✅ Nested Lists
✅ Nested Tuples
✅ Nested Dictionaries
✅ Mixing Lists, Tuples, and Dictionaries
2. Nested Lists
A nested list is a list inside another list. It is useful for storing matrix-like data, hierarchical lists, or multi-dimensional structures.
Example: 2D Matrix Representation
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # Accessing element at row 1, column 2 (6)
Output:
6
Looping Through a Nested List
pythonCopyEditfor row in matrix:
for num in row:
print(num, end=" ")
Output:
1 2 3 4 5 6 7 8 9
3. Nested Tuples
A nested tuple is a tuple inside another tuple. Since tuples are immutable, nested tuples are useful when you want to store structured data that should not change.
Example: Storing Student Records
students = (
("Alice", 22, "A"),
("Bob", 21, "B"),
("Charlie", 23, "A")
)
print(students[0][1]) # Accessing Alice's age (22)
Output:
22
Looping Through a Nested Tuple
for student in students:
print(f"Name: {student[0]}, Age: {student[1]}, Grade: {student[2]}")
Output:
Name: Alice, Age: 22, Grade: A
Name: Bob, Age: 21, Grade: B
Name: Charlie, Age: 23, Grade: A
4. Nested Dictionaries
A nested dictionary is a dictionary inside another dictionary. It is useful for storing hierarchical data, such as employee records, user profiles, or JSON-like structures.
Example: Employee Records
employees = {
"emp1": {"name": "Alice", "age": 25, "department": "HR"},
"emp2": {"name": "Bob", "age": 30, "department": "IT"},
"emp3": {"name": "Charlie", "age": 28, "department": "Finance"}
}
print(employees["emp2"]["department"]) # Accessing Bob's department (IT)
Output:
IT
Looping Through a Nested Dictionary
for emp_id, details in employees.items():
print(f"ID: {emp_id}")
for key, value in details.items():
print(f" {key}: {value}")
Output:
ID: emp1
name: Alice
age: 25
department: HR
ID: emp2
name: Bob
age: 30
department: IT
ID: emp3
name: Charlie
age: 28
department: Finance
5. Mixing Lists, Tuples, and Dictionaries
Python allows mixing different data structures inside each other for more complex storage.
Example: Student Data with Mixed Structures
students = [
{"name": "Alice", "grades": (85, 90, 88), "subjects": ["Math", "Science"]},
{"name": "Bob", "grades": (78, 82, 80), "subjects": ["English", "History"]}
]
print(students[1]["subjects"][0]) # Accessing Bob's first subject (English)
Output:
English
Looping Through Mixed Structures
for student in students:
print(f"Name: {student['name']}")
print(f"Grades: {student['grades']}")
print("Subjects:", ", ".join(student["subjects"]))
Output:
Name: Alice
Grades: (85, 90, 88)
Subjects: Math, Science
Name: Bob
Grades: (78, 82, 80)
Subjects: English, History
6. Modifying Nested Data Structures
Modifying a Nested List
matrix[1][2] = 99 # Changing 6 to 99
print(matrix)
Modifying a Nested Dictionary
employees["emp2"]["age"] = 31 # Changing Bob's age to 31
print(employees["emp2"])
7. Accessing Nested Data Safely
If you try to access a non-existent key, Python will raise a KeyError. Use .get() to avoid errors.
Example: Using .get() to Prevent Errors
print(employees.get("emp4", "Employee not found"))
Output:
Employee not found
8. Converting Between Nested Structures
Converting a Nested Dictionary to JSON
Python dictionaries can be converted to JSON using json.dumps().
import json
json_data = json.dumps(employees, indent=4)
print(json_data)
Converting a Nested List to a Dictionary
data = [["name", "Alice"], ["age", 25]]
dictionary = dict(data)
print(dictionary)
Output:
{'name': 'Alice', 'age': 25}
9. When to Use Nested Data Structures?
Use nested data structures when:
- You need to store complex data efficiently
- You are working with hierarchical or structured data
- You need JSON-like storage for APIs
Avoid nesting too deeply when:
- Data access becomes slow and complex
- It reduces code readability
