Open In App

Filter List of Python Dictionaries by Key in Python

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Filtering a list of dictionaries in Python based on a specific key is a common task in data manipulation and analysis. Whether you’re working with datasets or dictionaries, the ability to extract relevant information efficiently is crucial. In this article, we will explore some simple and commonly used methods to filter a list of dictionaries in Python by a specific key.

Filter List Of Dictionaries Python By Key In Python

Below, are the methods for Filter List Of Dictionaries Python By Key In Python.

Filter List Of Dictionaries Python By Key Using For Loop

In this approach, a for loop iterates through each dictionary in list_of_dicts. If the specified target_key exists in a dictionary (if target_key in d), that dictionary is appended to the filtered_list. This approach achieves the filtering based on the presence of the key using a simple for loop.

Python3




# List of dictionaries
list_of_dicts = [{'subject': 'Art', 'marks': 25}, {'subject': 'biology'}, {'marks': 30}]
 
# Specify the key for filtering (ensure case sensitivity)
target_key = 'subject'
 
# Initialize an empty list to store filtered dictionaries
filtered_list = []
 
# Filter using a for loop
for d in list_of_dicts:
    if target_key in d:
        filtered_list.append(d)
 
# Print the result
print("Filtered List:", filtered_list)


Output

Filtered List: [{'subject': 'Art', 'marks': 25}, {'subject': 'biology'}]


Filter List Of Dictionaries Python By Key Using List Comprehension

This method involves using a list comprehension to filter dictionaries based on the existence of a specified key.

Python3




# List of dictionaries
list_of_dicts = [{'name': 'A', 'class': 5}, {'name': 'B'}, {'class': 10}]
 
# Specify the key for filtering
target_key = 'name'
 
# Filter using list comprehension
filtered_list = [d for d in list_of_dicts if target_key in d]
 
# Print the result
print("Filtered List :", filtered_list)


Output

Filtered List : [{'name': 'A', 'class': 5}, {'name': 'B'}]


Filter List Of Dictionaries Python By Key Using Filter() Function

The filter function, combined with a lambda function, allows us to selectively include dictionaries based on the specified key.

Python3




# List of dictionaries
list_of_dicts = [{'name': 'Alice', 'age': 25}, {'name': 'Bob'}, {'age': 30}]
 
# Specify the key for filtering
target_key = 'name'
 
# Filter using filter and lambda
filtered_list = list(filter(lambda d: target_key in d, list_of_dicts))
 
# Print the result
print("Filtered List :", filtered_list)


Output

Filtered List : [{'name': 'Alice', 'age': 25}, {'name': 'Bob'}]


Filter List Of Dictionaries Python By Key Using map() Function

In this approach, map is used to apply a lambda function to each dictionary in list_of_dicts. The lambda function checks if the target_key exists in a dictionary, and if it does, the dictionary is returned; otherwise, None is returned. The final list comprehension is then used to filter out the None values, resulting in the filtered list.

Python3




# List of dictionaries
list_of_dicts = [{'subject': 'Art', 'marks': 25}, {'subject': 'biology'}, {'marks': 30}]
 
# Specify the key for filtering (ensure case sensitivity)
target_key = 'subject'
 
# Filter using map and lambda
filtered_list = list(map(lambda d: d if target_key in d else None, list_of_dicts))
filtered_list = [d for d in filtered_list if d is not None]
 
# Print the result
print("Filtered List:", filtered_list)


Output

Filtered List: [{'subject': 'Art', 'marks': 25}, {'subject': 'biology'}]


Conclusion

In this article we came to understand how to do filtering of a list of dictionaries by a specific key in Python . This can be achieved through various methods and we can decide which one to use by complexity of the filtering criteria and the desired output format. List comprehensions, lambda functions and many more provide flexible and efficient solutions for different scenarios.



Similar Reads

Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Python Program to extract Dictionaries with given Key from a list of dictionaries
Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
6 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" : 8}, {"Gfg" : 4, "is" : 10, "best" : 7}], K = "
9 min read
Filter List of Dictionaries Based on Key Values in Python
Filtering a list of dictionaries based on key values is a common task in Python, especially when working with data manipulation and analysis. In this article, we will explore five different methods to achieve this goal, each offering its own advantages and use cases. Whether you're a beginner or an experienced Python developer, these methods will p
3 min read
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: using list comprehension, the filter function, a
3 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
Convert a List of Dictionaries into a Set of Dictionaries
Python's versatility allows developers to manipulate data in various ways. When working with a list of dictionaries, there might be scenarios where you want to convert it into a set of dictionaries to eliminate duplicates or for other reasons. In this article, we'll explore three different methods to achieve this goal with code examples. Convert A
3 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 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 by narrowing down the dataset to include only relev
2 min read
Python - Filter key's value from other key
Sometimes, while working with Python dictionary, we can have a problem in which we need to extract a value from dictionary list of the key on basis of some other key equality. This kind of problem is common in domains that include data, for e.g web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [{'g
7 min read
Practice Tags :
three90RightbarBannerImg