Iterate Over Nested Dictionary with List in Python (Example)

In this tutorial, you’ll learn how to iterate over a nested dictionary that contains lists using the Python programming language.

The table of contents is structured as follows:

Let’s dive into it!

Data Initialization

Let’s consider the following nested dictionary:

data = {
    'fruits': ['apple', 'banana', 'orange'],
    'vegetables': ['carrot', 'broccoli', 'spinach'],
    'colors': ['red', 'green', 'blue']
}

Iterating Over Nested Dictionary with List

To iterate over a nested dictionary with lists in Python, you can follow these steps:

  1. Access the outer dictionary using a loop.
  2. Access the inner dictionary within the outer loop.
  3. Access the elements within the list using another loop.

Example: Iterate Over Nested Dictionary with List

To iterate over this nested dictionary, you can use the following code using a nested for loop:

for category, items in data.items():
    print(f"Category: {category}")
    print("Items:")
    for item in items:
        print(f" {item}")
    print()
 
#Category: fruits
#Items:
# apple
# banana
# orange
 
#Category: vegetables
#Items:
# carrot
# broccoli
# spinach
 
#Category: colors
#Items:
# red
# green
# blue

The example demonstrates how to iterate over the nested dictionary with lists and print the category name along with the items within each category.

Video, Further Resources & Summary

Do you need more explanations on iterating over a nested dictionary with a list in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

The YouTube video will be added soon.

Furthermore, you could have a look at some of the other tutorials on Statistics Globe:

This post has shown how to iterate over a nested dictionary with lists in Python. In case you have further questions, you may leave a comment below.

Ömer Ekiz Informatics Expert

This page was created in collaboration with Ömer Ekiz. You may have a look at Ömer’s author page to read more about his academic background and the other articles he has written for Statistics Globe.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top