Learn Python in 30 Days — Day 13: Nested Structures & Looping

 Learn Python in 30 Days — Day 13: Nested Structures & Looping

Welcome to Day 13 of the Learn Python in 30 Days series!


Yesterday, we explored how to use dictionaries to store key/value data in a clean, flexible way.
Today, we take that one step further by combining structures together and looping through nested data.

If you’re aiming to become fluent in Python, understanding nested structures is essential. It’s how real-world data is represented from JSON APIs and databases to configuration files and game state tracking.

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

Step 1 – What Are Nested Structures?

A nested structure is simply one data structure inside another.

Let’s start with a simple list:

numbers = [1, 2, 3, 4]

Now imagine each number needs a label. A dictionary might work better:

number_info = {"id": 1, "label": "One"}

But what if we have multiple of those dictionaries?
You can place them inside a list:

numbers = [ {"id": 1, "label": "One"}, {"id": 2, "label": "Two"}, {"id": 3, "label": "Three"}, ]

Now you have a list of dictionaries one of the most common Python patterns for real-world data.

Here’s an example program you can run in Python to demonstrate that concept in action, showing both the creation and the output from looping through your list of dictionaries:

# Basic list of dictionaries example numbers = [ {"id": 1, "label": "One"}, {"id": 2, "label": "Two"}, {"id": 3, "label": "Three"}, {"id": 4, "label": "Four"} ] # Access a specific item print("\nAccessing a specific element:") print(numbers[2]["label"]) # Output: Three

Output:

Accessing a specific element: Three
Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Step 2 – Looping Through Nested Data

You’ve already learned how to loop through lists and dictionaries separately.
Now we’ll combine those skills.

Example: print each number’s label and ID.

numbers = [ {"id": 1, "label": "One"}, {"id": 2, "label": "Two"}, {"id": 3, "label": "Three"}, ] for item in numbers: print(f"ID: {item['id']} → Label: {item['label']}")

Output:

ID: 1 Label: One ID: 2 Label: Two ID: 3 Label: Three

Here’s what’s happening:

  • The for loop iterates through each dictionary in the list.

  • item refers to each dictionary in turn.

  • You access each field with item['id'] and item['label'].

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Step 3 – Nested Loops (Looping Inside Loops)

Let’s make it more interesting.

What if each number dictionary also contained a list?

numbers = [ {"id": 1, "label": "One", "facts": ["Odd", "First natural number"]}, {"id": 2, "label": "Two", "facts": ["Even", "Only even prime number"]}, {"id": 3, "label": "Three", "facts": ["Odd", "Triangular number"]}, ]

Now you need a loop inside a loop to print everything:

for num in numbers: print(f"\nID: {num['id']} → {num['label']}") print("Facts:") for fact in num["facts"]: print(f" - {fact}")

Output:

ID: 1 → One Facts: - Odd - First natural number ID: 2 → Two Facts: - Even - Only even prime number ID: 3 → Three Facts: - Odd - Triangular number

Each time you loop over a dictionary, you can open a second loop to go deeper into its lists.

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Step 4 – Dictionaries Inside Dictionaries

Nesting isn’t limited to lists, you can nest dictionaries inside dictionaries too.

Example: imagine a mini contact book with contact details grouped neatly:

contacts = { "Matty": {"email": "matty@example.com", "phone": "123-456"}, "Alex": {"email": "alex@example.com", "phone": "987-654"}, }

Loop through this nested dictionary like so:

for name, info in contacts.items(): print(f"\n{name}") for key, value in info.items(): print(f" {key.title()}: {value}")

Output:

Matty Email: matty@example.com Phone: 123-456 Alex Email: alex@example.com Phone: 987-654

Notice:

  • The outer loop iterates through each contact.

  • The inner loop goes through each contact’s details.

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Step 5 – Pretty Printing Complex Data

As your structures grow, printing them with print() can become messy.
Python includes a very handy module called pprint (pretty print).

import pprint data = { "users": [ {"name": "Matty", "skills": ["Python", "Electronics", "Blogging"]}, {"name": "Sarah", "skills": ["C++", "3D Printing", "Robotics"]}, ] } pprint.pprint(data)

Output (nicely formatted):

{'users': [{'name': 'Matty', 'skills': ['Python', 'Electronics', 'Blogging']}, {'name': 'Sarah', 'skills': ['C++', '3D Printing', 'Robotics']}]}

This is especially helpful when debugging nested dictionaries, JSON responses, or API data.

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Step 6 – Mini Project: Student Database

Let’s put it all together with a small nested structure project.

Goal: Create a student database that stores multiple students, each with their name, ID, and list of grades.

students = [ {"name": "Alice", "id": 101, "grades": [85, 90, 92]}, {"name": "Bob", "id": 102, "grades": [78, 82, 88]}, {"name": "Charlie", "id": 103, "grades": [92, 95, 97]}, ] for student in students: print(f"\n{student['name']} (ID: {student['id']})") average = sum(student["grades"]) / len(student["grades"]) print(f"Grades: {student['grades']}") print(f"Average: {round(average, 2)}")

Output:

Alice (ID: 101) Grades: [85, 90, 92] Average: 89.0 Bob (ID: 102) Grades: [78, 82, 88] Average: 82.67 Charlie (ID: 103) Grades: [92, 95, 97] Average: 94.67
Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

💡 Tips

  • Use meaningful variable names when nesting deeply (e.g., student, course, item, entry).

  • If your nesting gets more than 2–3 levels deep, consider breaking it into smaller parts or using classes.

  • The json module can load and save nested structures easily (we’ll explore that later)

Next up — Day 14 – Week 2 Review

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

You can see the full series here Learn Python in 30 Days series!

Hope you have enjoyed this post, thanks Matty

Comments

Popular posts from this blog

Math Behind Logic Gates

6502 - Part 2 Reset and Clock Circuit

Building a 6502 NOP Test