Python Filter List of Dictionaries Based on Key Value
Last Updated :
13 Feb, 2024
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: using list comprehension, the filter function, and a traditional for loop.
Python Filter List Of Dictionaries Based On Key Value
Below, are the methods to Python Filter List Of Dictionaries Based On Key Value.
Create a List of Dictionaries
here, we are creating a List of Dictionaries.
Python3
data = [
{ 'name' : 'Alice' , 'age' : 25 },
{ 'name' : 'Bob' , 'age' : 30 },
{ 'name' : 'Charlie' , 'age' : 22 },
{ 'name' : 'David' , 'age' : 35 }
]
|
Filter List Of Dictionaries Based On Key-Value Using a For Loop
While list comprehensions and the filter
the function provides concise solutions, using a for loop can be a more explicit and customizable approach. Here’s an example:
In this example, the for loop iterates through each dictionary in the data
list and the if statement checks if the ‘age’ key has a value greater than 25. If true, the dictionary is appended to the filtered_data
list.
Python3
filtered_data = []
for entry in data:
if entry[ 'age' ] > 25 :
filtered_data.append(entry)
print (filtered_data)
|
Output
[{'name': 'Bob', 'age': 30}, {'name': 'David', 'age': 35}]
Filter List Of Dictionaries Based On Key-Value Using List Comprehension
List comprehension is a concise and readable way to create lists in Python. It allows us to filter elements from an existing list based on certain conditions. Here’s an example of using list comprehension to filter a list of dictionaries:
In this example, the list comprehension iterates through each dictionary in the data
list and includes only those dictionaries where the ‘age’ key has a value greater than 25.
Python3
filtered_data = [entry for entry in data if entry[ 'age' ] > 25 ]
print (filtered_data)
|
Output
[{'name': 'Bob', 'age': 30}, {'name': 'David', 'age': 35}]
Filter List Of Dictionaries Based On Key Value Using the Filter Function
The filter
function is a built-in Python function that constructs an iterator from elements of an iterable for which a function returns true. To use it with a list of dictionaries, we need a filtering function. Here’s an example:
In this example, the filter_by_age
function checks if the ‘age’ key in each dictionary is greater than 25. The filter
function then applies this filtering function to each element in the data
list.
Python3
def filter_by_age(entry):
return entry[ 'age' ] > 25
filtered_data = list ( filter (filter_by_age, data))
print (filtered_data)
|
Output
[{'name': 'Bob', 'age': 30}, {'name': 'David', 'age': 35}]
Share your thoughts in the comments
Please Login to comment...