How To Iterate Through A Dictionary Inside A List In Python

In Python, a dictionary is a mutable, unordered collection of key-value pairs, where each key must be unique.

A list is an ordered, mutable collection of objects. You can have a list containing dictionaries, and you might encounter situations where you need to iterate through such a list to manipulate or analyze the data. In this tutorial, we will learn how to iterate through a dictionary inside a list in Python.

Step 1: Create a list of dictionaries

First, let’s create a simple list containing dictionaries. Each dictionary in the list will represent a person with their first name, last name, and age.

Step 2: Iterate through the dictionaries in the list

To iterate through the dictionaries in the list, you can use a simple for loop.

Output:

{'first_name': 'John', 'last_name': 'Doe', 'age': 30}
{'first_name': 'Jane', 'last_name': 'Doe', 'age': 28}
{'first_name': 'Alice', 'last_name': 'Johnson', 'age': 24}

Step 3: Access individual elements in the dictionary

To access individual elements in each dictionary, you can use their keys.

Output:

John Doe is 30 years old.
Jane Doe is 28 years old.
Alice Johnson is 24 years old.

Step 4: Iterate through the key-value pairs of the dictionary

To iterate through the key-value pairs of the dictionary while processing each dictionary in the list, you can use the items() method.

Output:

first_name: John
last_name: Doe
age: 30
---
first_name: Jane
last_name: Doe
age: 28
---
first_name: Alice
last_name: Johnson
age: 24
---

Full code:

Conclusion

In this tutorial, we learned how to iterate through a list of dictionaries in Python. We practiced accessing individual elements within the dictionaries and iterating through the key-value pairs of the dictionaries. This technique is useful when you need to process or analyze nested data structures.