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 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 | Find dictionary matching value in list
The problem of getting only the suitable dictionary that has a particular value of the corresponding key is quite common when one starts working with a dictionary in Python. Let's discuss certain ways in which this task can be performed. Method 1: Get a list of values from a List of Dictionary using
7 min read
Element Occurrence in Dictionary of List Values - Python
We are having a dictionary of list we need to find occurrence of all elements. For example, d = {'a': [1, 2, 3, 1], 'b': [3, 4, 1], 'c': [1, 5, 6]} we need to count the occurrence of all elements in dictionary list so that resultant output should be {'a': 2, 'b': 1, 'c': 1}. Using a Dictionary Compr
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 efficientl
2 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,
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
Python - Append Multitype Values in Dictionary
There are cases where we may want to append multiple types of values, such as integers, strings or lists to a single dictionary key. For example, if we are creating a dictionary to store multiple types of data under the same key, such as user details (e.g., age, address, and hobbies), we need to han
2 min read
Sort List of Dictionaries by Multiple Keys - Python
We are given a list of dictionaries where each dictionary contains various keys and our task is to sort the list by multiple keys. Sorting can be done using different methods such as using the sorted() function, a list of tuples, itemgetter() from the operator module. For example, if we have the fol
3 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
Python | Unique dictionary filter in list
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 ite
3 min read