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.
1 2 3 4 5 |
people = [ {'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 2: Iterate through the dictionaries in the list
To iterate through the dictionaries in the list, you can use a simple for loop.
1 2 |
for person in people: print(person) |
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.
1 2 |
for person in people: print(f"{person['first_name']} {person['last_name']} is {person['age']} years old.") |
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.
1 2 3 4 |
for person in people: for key, value in person.items(): print(f"{key}: {value}") print("---") |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
people = [ {'first_name': 'John', 'last_name': 'Doe', 'age': 30}, {'first_name': 'Jane', 'last_name': 'Doe', 'age': 28}, {'first_name': 'Alice', 'last_name': 'Johnson', 'age': 24} ] for person in people: print(f"{person['first_name']} {person['last_name']} is {person['age']} years old.") print("\n---\n") for person in people: for key, value in person.items(): print(f"{key}: {value}") print("---") |
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.