Iterating List of Python Dictionaries
Last Updated :
19 Feb, 2024
Iteration of the list of dictionaries is a very common practice that every developer performs while encountering with dictionary data. In this article, we will explore how to iterate through a list of dictionaries.
Iterating List Of Dictionaries in Python
Below are some of the ways by which we can iterate list of dictionaries in Python:
- Using a simple loop
- Using a list comprehension
- Using itertools.chain() Method
Iterate List Of Dictionaries Using a Simple Loop
In this example, a list named movies
contains dictionaries representing movie information. Through nested loops, the code iterates over each dictionary and unpacks its key-value pairs, printing the details of each movie, including title, director, genre, and year.
Python3
movies = [
{"title": "The Shawshank Redemption",
"director": "Frank Darabont", "genre": "Drama", "year": 1994},
{"title": "The Godfather", "director": "Francis Ford Coppola",
"genre": "Crime", "year": 1972}
]
# Iterating through the list of dictionaries and unpacking key-value pairs
for movie in movies:
for key, value in movie.items():
print(f"{key}: {value}")
Outputtitle: The Shawshank Redemption
director: Frank Darabont
genre: Drama
year: 1994
title: The Godfather
director: Francis Ford Coppola
genre: Crime
year: 1972
Iterate List Of Dictionaries Using a List Comprehension
In this example, a list named movies
contains dictionaries representing movie information. The code utilizes a list comprehension to iterate over each dictionary, unpacking its key-value pairs, and printing them in a concise manner using the print
function.
Python3
movies = [
{"title": "The Shawshank Redemption",
"director": "Frank Darabont", "genre": "Drama", "year": 1994},
{"title": "The Godfather", "director": "Francis Ford Coppola",
"genre": "Crime", "year": 1972}
]
# Iterating through the list of dictionaries and unpacking key-value pairs
_ = [print(key, value) for d in movies for key, value in d.items()]
Outputtitle The Shawshank Redemption
director Frank Darabont
genre Drama
year 1994
title The Godfather
director Francis Ford Coppola
genre Crime
year 1972
Iterate List Of Dictionaries Using itertools.chain() Method
In this example, the itertools
module's chain()
function is used to iterate through the list of dictionaries (movies
). The nested generator expression and chain.from_iterable
method unpack key-value pairs from each dictionary, and the resulting pairs are iterated through, printing the details of each movie, including title, director, genre, and year.
Python3
from itertools import chain
movies = [
{"title": "The Shawshank Redemption",
"director": "Frank Darabont", "genre": "Drama", "year": 1994},
{"title": "The Godfather", "director": "Francis Ford Coppola",
"genre": "Crime", "year": 1972},
{"title": "Inception", "director": "Christopher Nolan",
"genre": "Sci-Fi", "year": 2010},
{"title": "Pulp Fiction", "director": "Quentin Tarantino",
"genre": "Crime", "year": 1994}
]
# Iterating through the list of dictionaries and unpacking key-value pairs
for key, value in chain.from_iterable(d.items() for d in movies):
print(key, value)
Output:
title The Shawshank Redemption
director Frank Darabont
genre Drama
year 1994
title The Godfather
director Francis Ford Coppola
genre Crime
year 1972
title Inception
director Christopher Nolan
genre Sci-Fi
year 2010
title Pulp Fiction
director Quentin Tarantino
genre Crime
year 1994
Conclusion
This article, explored the efficient iteration methods through a list of dictionaries in Python, covering key concepts such as Lists of Dictionaries, Dictionary Unpacking, and Iterating through Lists. The provided examples, including student information, book details, and movie records, demonstrated the practical application of these concepts.We've seen the practical application of these concepts with examples, showcasing how to efficiently handle structured data using this approach.
Similar Reads
Filter List Of Dictionaries in Python
Filtering a list of dictionaries is a fundamental programming task that involves selecting specific elements from a collection of dictionaries based on defined criteria. This process is commonly used for data manipulation and extraction, allowing developers to efficiently work with structured data b
2 min read
Filter List of Python Dictionaries by Key in Python
In Python, filtering a list of dictionaries based on a specific key is a common task when working with structured data. In this article, weâll explore different ways to filter a list of dictionaries by key from the most efficient to the least. Using List Comprehension List comprehension is a concise
3 min read
Python - Convert List to List of dictionaries
We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into
4 min read
Python - Distinct Flatten dictionaries
Sometimes, while working with dictionaries, we can have keys which in itself is a part of very complex nestings and we wish to extract all the keys and values of particular key nesting into a separate list. This kind of problem can have applications in many domains such as web development. Lets disc
6 min read
Removing Dictionary from List of Dictionaries - Python
We are given a list of dictionaries, and our task is to remove specific dictionaries based on a condition. For instance given the list: a = [{'x': 10, 'y': 20}, {'x': 30, 'y': 40}, {'x': 50, 'y': 60}], we might want to remove the dictionary where 'x' equals 30 then the output will be [{'x': 10, 'y':
3 min read
Get first K items in dictionary = Python
We are given a dictionary and a number K, our task is to extract the first K key-value pairs. This can be useful when working with large dictionaries where only a subset of elements is needed. For example, if we have: d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} and K = 2 then the expected output would be:
2 min read
Python | Sum list of dictionaries with same key
You have given a list of dictionaries, the task is to return a single dictionary with sum values with the same key. Let's discuss different methods to do the task. Method #1: Using reduce() + operator Step-by-step approach: Import necessary modules - collections, functools, and operator.Initialize a
7 min read
Python Filter List of Dictionaries Based on Key Value
Python, a versatile and powerful programming language, offers multiple ways to manipulate and process data. When working with a list of dictionaries, you may often need to filter the data based on specific key-value pairs. In this article, we will explore three different methods to achieve this task
3 min read
Python - Convert List of Dictionaries to List of Lists
We are given list of dictionaries we need to convert it to list of lists. For example we are given a list of dictionaries a = [{'name': 'Geeks', 'age': 25}, {'name': 'Geeks', 'age': 30}] we need to convert it in list of list so that the output becomes[['Geeks',25],['Geeks;'30]]. Using List Comprehen
3 min read
Python | Initialize list with empty dictionaries
While working with Python, we can have a problem in which we need to initialize a list of a particular size with empty dictionaries. This task has it's utility in web development to store records. Let's discuss certain ways in which this task can be performed. Method #1 : Using {} + "*" operator Thi
5 min read