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 by narrowing down the dataset to include only relevant information.
Filter List Of Dictionaries in Python
Below, are the examples of Filter List Of Dictionaries in Python.
- Using List Comprehension
- Using Filter() and Lambda Function
- Using Pandas Library
Filter List Of Dictionaries Using List Comprehension
In this example, the below code filters a list of dictionaries (`original_list`) to create a new list (`filtered_list`) containing only dictionaries where the ‘age’ key is greater than 25 and then prints the result.
Python3
original_list = [{ 'name' : 'Alice' , 'age' : 25 }, { 'name' : 'Bob' , 'age' : 30 }, { 'name' : 'Charlie' , 'age' : 22 }] filtered_list = [d for d in original_list if d[ 'age' ] > 25 ] print (filtered_list) |
[{'name': 'Bob', 'age': 30}]
Filter List Of Dictionaries Using Filter() and Lambda Function
In this example, below code filters a list of dictionaries (`original_list`) using the `filter()` function and a lambda expression to include only dictionaries where the ‘age’ key is greater than 25. The result is stored in `filtered_list` .
Python3
original_list = [{ 'name' : 'Alice' , 'age' : 25 }, { 'name' : 'Bob' , 'age' : 30 }, { 'name' : 'Charlie' , 'age' : 22 }] filtered_list = list ( filter ( lambda d: d[ 'age' ] > 25 , original_list)) print (filtered_list) |
[{'name': 'Bob', 'age': 30}]
Filter List Of Dictionaries Using Pandas Library
In this example , below code converts a list of dictionaries (`original_list`) into a Pandas DataFrame (`df`) and then filters the DataFrame to include only rows where the ‘age’ column is greater than 25. The filtered result is converted back to a list of dictionaries (`filtered_df`) .
Python3
import pandas as pd original_list = [{ 'name' : 'Alice' , 'age' : 25 }, { 'name' : 'Bob' , 'age' : 30 }, { 'name' : 'Charlie' , 'age' : 22 }] df = pd.DataFrame(original_list) filtered_df = df[df[ 'age' ] > 25 ].to_dict(orient = 'records' ) print (filtered_df) |
Output
[{'name': 'Bob', 'age': 30}]