
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate Through List of Dictionaries in Python
In this article, we will learn various methods to iterate through the list of dictionaries in Python. When working with data in Python, it is very common to encounter scenarios where you have a list of dictionaries. Each dictionary represents an individual data entry, and you need to perform operations or extract specific information from these dictionaries.
Using a For Loop and Dictionary Access Methods
The approach is to use a for loop to iterate through each dictionary in the list. Inside the loop, we can use dictionary access methods like keys(), values(), or items() to retrieve the keys, values, or key?value pairs, respectively.
Syntax
keys()
dictionary.keys()
keys() method returns a view object that contains the keys of the dictionary.
values()
dictionary.values()
values() method returns a view object that contains the values of the dictionary.
items()
dictionary.items()
items() method returns a view object that contains the key?value pairs of the dictionary as tuples.
Explanation
Create a list of dictionary `list_of_dict`.
Iterate through the list of dictionaries using for loop.
Now we use the items() method to access the key?value pairs in each dictionary.
Print the Key, Value pairs.
Example
list_of_dict = [ {"course": "DBMS", "price": 1500}, {"course": "Python", "price": 2500}, {"course": "Java", "price": 2500}, ] for dict in list_of_dict: for key, value in dict.items(): print(key, ":", value) print("")
Output
course : DBMS price : 1500 course : Python price : 2500 course : Java price : 2500
Using List Comprehension
List comprehension provides a way to iterate through the list of dictionaries and perform operations on each dictionary. Now we will use list comprehension to iterate over the entire list
Syntax:
[expression for element in iterable]
Iterable: It can be a list, set, tuple, or any Python iterable.
Element: item present in the iterable.
Expression: Operation that we want to perform on the element
Explanation
Create a list of dictionary `list_of_dict`.
Use the list comprehensions to iterate over the list and fetch information in the dictionary in separate lists.
Example
list_of_dict = [ {"course": "DBMS", "price": 1500}, {"course": "Python", "price": 2500}, {"course": "Java", "price": 2500}, ] # iterating through each dictionary course= [dictionary["course"] for dictionary in list_of_dict] price= [dictionary["price"] for dictionary in list_of_dict] print(course) print(price)
Output
['DBMS', 'Python', 'Java'] [1500, 2500, 2500]
Using the map() Function
The map() function is a built?in python function that applies a specified function to each item in an iterable in our case the iterable is a list and returns an iterator that yields the results. It takes two arguments: the function to apply and the iterable.
Syntax
map(function, iterable)
Iterable: The sequence of items to which the specified function will be applied.
Function: The function we want to apply to the items in the iterator.
Explanation
Create a list of dictionaries
Pass the function and iterable i.e. list of dictionaries to the map() method.
Use the list() method to convert the result given by the map() into a list.
Example
list_of_dict = [ {"course": "DBMS", "price": 1500}, {"course": "Python", "price": 2500}, {"course": "Java", "price": 2500}, ] def func(dict): return dict["course"] # applying the function to all the dictionaries present in the list. course = list(map(func, list_of_dict)) print(course)
Output
['DBMS', 'Python', 'Java']
Using the pandas Library
The DataFrame() constructor will convert the list of dictionaries into a data frame. Each dictionary in the list will be represented as a row in the data frame. Iterating the list of dictionaries can be convenient when dealing with large datasets.
Syntax
pd.DataFrame(iterable)
Iterable:Sequence of elements. For example list, tuple.
Explanation
Create a list of dictionaries
Pass the list of dictionaries to the DataFrame() constructor in the pandas library.
The constructor will return a data frame object with each dictionary as a row in the data frame
Example
import pandas as pd list_of_dict = [ {"course": "DBMS", "price": 1500}, {"course": "Python", "price": 2500}, {"course": "Java", "price": 2500}, ] df = pd.DataFrame(list_of_dict) print(df)
Output
course price 0 DBMS 1500 1 Python 2500 2 Java 2500
Using from_records() Method in DataFrame class of the pandas library
In this approach we will use the from_records() method. The pd.DataFrame.from_records() method in pandas allows us to create a DataFrame from a list of records (tuples or structured arrays) or an iterable.
Syntax
pd.DataFrame.from_records(data)
Data: Structured array, List of dictionaries in this case.
Explanation
Create a list of dictionaries.
Pass the list to the from_records() method
The from_records() method will return a data frame with each dictionary in the list as a row in the data frame.
Example
import pandas as pd list_of_dict = [ {"course": "DBMS", "price": 1500}, {"course": "Python", "price": 2500}, {"course": "Java", "price": 2500}, ] df = pd.DataFrame.from_records(list_of_dict) print(df)
Output
course price 0 DBMS 1500 1 Python 2500 2 Java 2500
Conclusion
Throughout this article, we explored different approaches including looping, list comprehension and even leveraging the capabilities of the pandas library to iterate through a list of dictionaries. Happy learning!