Filtering a List of Dictionary on Multiple Values in Python
Last Updated :
07 Feb, 2024
Filtering a list of dictionaries is a common task in programming, especially when dealing with datasets. Often, you may need to extract specific elements that meet certain criteria. In this article, we'll explore four generally used methods for filtering a list of dictionaries based on multiple values, providing code examples in Python.
Filtering A List Of Dictionaries Based On Multiple Values
Below, are the method of Filtering A List Of Dictionaries Based On Multiple Values in Python.
Filtering A List Of Dictionaries Based On Multiple Values Using List Comprehension
List comprehension is a concise and efficient way to create lists in Python. It can be leveraged to filter a list of dictionaries based on multiple values.
Example: In this example, the code creates a list of dictionaries named 'data' and filters it, retaining only dictionaries where the 'age' is greater than 25 and the 'city' is 'New York'. The resulting filtered data is stored in the 'filtered_data' variable and printed.
Python3
data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'San Francisco'},
{'name': 'Charlie', 'age': 28, 'city': 'New York'},
# ... additional dictionaries ...
]
filtered_data = [item for item in data if item['age'] > 25 and item['city'] == 'New York']
print(filtered_data)
Output[{'name': 'Charlie', 'age': 28, 'city': 'New York'}]
Filtering A List Of Dictionaries Based On Multiple Values Using Filter and Lambda Function
The filter
function in combination with a lambda function is another approach for filtering lists based on multiple criteria.
Example : In this example, The code defines a list of dictionaries called 'data' and uses the `filter` function with a lambda expression to create 'filtered_data', containing dictionaries where the 'age' is greater than 25 and the 'city' is 'New York'.
Python3
data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'San Francisco'},
{'name': 'Charlie', 'age': 28, 'city': 'New York'},
# ... additional dictionaries ...
]
filtered_data = list(filter(lambda x: x['age'] > 25 and x['city'] == 'New York', data))
print(filtered_data)
Output[{'name': 'Charlie', 'age': 28, 'city': 'New York'}]
Filtering A List Of Dictionaries Based On Multiple Values Using Pandas DataFrame
If your data is structured and large, using a Pandas DataFrame can provide a powerful solution for filtering.
Example : In this example, The code uses the Pandas library to create a DataFrame from the list of dictionaries named 'data'. It then filters the DataFrame to include rows where the 'age' is greater than 25 and the 'city' is 'New York'.
Python3
import pandas as pd
data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'San Francisco'},
{'name': 'Charlie', 'age': 28, 'city': 'New York'},
# ... additional dictionaries ...
]
df = pd.DataFrame(data)
filtered_data = df[(df['age'] > 25) & (df['city'] == 'New York')].to_dict('records')
print(filtered_data)
Output
[{'name': 'Charlie', 'age': 28, 'city': 'New York'}]
Filtering A List Of Dictionaries Based On Multiple Values Using custom Function
Create a custom filtering function that accepts a dictionary and returns True
if it meets the criteria.
Example : In this example, The code defines a custom filtering function named 'custom_filter' that checks if the 'age' is greater than 25 and the 'city' is 'New York' for a given dictionary. It then applies this filter function to the list of dictionaries called 'data' using the `filter` function, creating 'filtered_data'.
Python3
def custom_filter(item):
return item['age'] > 25 and item['city'] == 'New York'
data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'San Francisco'},
{'name': 'Charlie', 'age': 28, 'city': 'New York'},
# ... additional dictionaries ...
]
filtered_data = list(filter(custom_filter, data))
print(filtered_data)
Output[{'name': 'Charlie', 'age': 28, 'city': 'New York'}]
Conclusion
Filtering a list of dictionaries based on multiple values is a common requirement in programming. The choice of method depends on the specific use case, data size, and personal preference. These four methods - list comprehension, filter with lambda function, Pandas DataFrame, and custom filtering function - provide versatile options for efficiently extracting relevant information from your data.
Similar Reads
Python | Find dictionary matching value in list Finding a dictionary with a specific value in a list of dictionaries involves searching through the list and matching a key-value pair in each dictionary. For example, given the list of dictionaries [{âCourseâ: âC++â, âAuthorâ: âJerryâ}, {âCourseâ: âPythonâ, âAuthorâ: âMarkâ}], you may want to find
3 min read
Get Python Dictionary Values as List - Python We are given a dictionary where the values are lists and our task is to retrieve all the values as a single flattened list. For example, given the dictionary: d = {"a": [1, 2], "b": [3, 4], "c": [5]} the expected output is: [1, 2, 3, 4, 5]Using itertools.chain()itertools.chain() function efficiently
2 min read
Python - Filter dictionaries by values in Kth Key in list Given a list of dictionaries, the task is to write a Python program to filter dictionaries on basis of elements of Kth key in the list. Examples: Input : test_list = [{"Gfg" : 3, "is" : 5, "best" : 10}, {"Gfg" : 5, "is" : 1, "best" : 1}, {"Gfg" : 8, "is" : 3, "best" : 9}, {"Gfg" : 9, "is" : 9, "best
9 min read
Get List of Values From Dictionary - Python We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3].Using dict.values()We can use dict.values() along with the list() function to get the list. Here, t
2 min read
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
Unique Dictionary Filter in List - Python We are given a dictionary in list we need to find unique dictionary. For example, a = [ {"a": 1, "b": 2}, {"a": 1, "b": 2}, {"c": 3}, {"a": 1, "b": 3}] so that output should be [{'a': 1, 'b': 2}, {'a': 1, 'b': 3}, {'c': 3}].Using set with frozensetUsing set with frozenset, we convert dictionary item
3 min read
Filter Dictionary Key based on the Values in Selective List - Python We are given a dictionary where each key is associated with a value and our task is to filter the dictionary based on a selective list of values. We want to retain only those key-value pairs where the value is present in the list. For example, we have the following dictionary and list: d = {'apple':
3 min read
Python - Print dictionary of list values In this article, we will explore various ways on How to Print Dictionary in Python of list values. A dictionary of list values means a dictionary contains values as a list of dictionaries in Python. Example: {'key1': [{'key1': value,......,'key n': value}........{'key1': value,......,'key n': value}
4 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 - Filter odd elements from value lists in dictionary Sometimes, while working with Python dictionaries we can have problem in which we need to perform the removal of odd elements from values list of dictionaries. This can have application in many domains including web development. Lets discuss certain ways in which this task can be performed. Method
6 min read