Python Mastery – From Basics to Brilliance / Data Structures in Python

Nested Data Structures

A nested data structure is simply one data structure that contains another.

Examples:

  • A list of lists

  • A dictionary of lists

  • A list of dictionaries

  • A dictionary of dictionaries

📦 These allow you to organize and access multi-dimensional data effectively.


📚 Common Types of Nested Structures

🧮 List Inside a List

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix[0])       # ➤ [1, 2, 3]
print(matrix[1][2])    # ➤ 6

📌 Use Case: 2D grids, tables, game boards.


📋 List of Dictionaries

students = [
    {"name": "Alice", "age": 22},
    {"name": "Bob", "age": 23}
]

print(students[1]['name'])   # ➤ Bob

📌 Use Case: Tabular data like CSV rows, API data, records.


📜 Dictionary with List Values

courses = {
    "Python": ["Basics", "OOP", "Web Dev"],
    "Java": ["Core", "Spring", "Hibernate"]
}

print(courses['Python'][1])  # ➤ OO

📌 Use Case: Grouping related topics or options under a category.


🧾 Dictionary of Dictionaries

employee = {
    "emp1": {"name": "Alice", "dept": "HR"},
    "emp2": {"name": "Bob", "dept": "IT"}
}

print(employee["emp2"]["dept"])  # ➤ IT

📌 Use Case: Representing key-value-based relational data.


🧪 How to Traverse Nested Structures

🔄 Loop through List of Lists

matrix = [[1, 2], [3, 4]]
for row in matrix:
    for val in row:
        print(val)

🔄 Loop through List of Dicts

for student in students:
    print(student['name'])

🔄 Loop through Dict of Lists

for course, topics in courses.items():
    print(f"{course} includes:")
    for topic in topics:
        print(f"  - {topic}")

🛠️ Best Practices

✅ Keep data structured and readable

✅ Access nested elements with safe indexing (get(), try-except)

✅ Use functions or helper methods to extract deep values

✅ Use list comprehensions for concise filtering/extraction


🧹 Example: Extract All Ages from a List of Dictionaries

students = [
    {"name": "Alice", "age": 22},
    {"name": "Bob", "age": 23},
    {"name": "Charlie", "age": 21}
]

ages = [student['age'] for student in students]
print(ages)  # ➤ [22, 23, 21]

🧰 Built-in Functions Helpful for Nested Data

Function

Use Case

len()

Check length of nested elements

type()

Identify nested data types

get()

Safely access dictionary keys

isinstance()

Verify type before access

json.loads()

Convert JSON string to Python