Open In App

Python - Remove dictionary from a list of dictionaries if a particular value is not present

Last Updated : 15 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

We are given a list of dictionaries we need to remove the dictionary if a particular value is not present in it. For example, we are having a list of dictionaries a = [{'a': 1}, {'b': 2}, {'c': 3, 'd': 4}, {'e': 5}] the output should be [{'c': 3, 'd': 4}]. We can use multiple method like list comprehension, filter and various other approaches.

Using List Comprehension

List comprehension filters list by retaining only those dictionaries that contain the desired value. It checks each dictionary's values and includes it in new list if value is present.

Python
a = [{'a': 1}, {'b': 2}, {'c': 3, 'd': 4}, {'e': 5}]

# Retain dictionaries that contain the value 3
f = [d for d in a if 3 in d.values()]
print(f) 

Output
[{'c': 3, 'd': 4}]

Explanation:

  • List comprehension iterates over each dictionary in a, retaining only those where the value 3 is present in d.values().
  • Resulting list f is printed, containing {'c': 3, 'd': 4} as it meets the condition.

Using filter() Function

filter() function iterates over the list, applying a condition to keep only dictionaries containing the desired value. It creates a filtered result, which can be converted back to a list for further use.

Python
d = [{'a': 1}, {'b': 2}, {'c': 3, 'd': 4}, {'e': 5}]

# Retain dictionaries containing the value 3
f = list(filter(lambda d: 3 in d.values(), d))
print(f)  

Output
[{'c': 3, 'd': 4}]

Explanation:

  • filter() function applies a lambda function to each dictionary in the list d, checking if the value 3 exists in d.values(), and retains those that satisfy the condition.
  • Filtered result is converted to a list f and printed, resulting in f = [{'c': 3, 'd': 4}]

Using for Loop with Conditional Check

for loop iterates over a copy of the list to safely check each dictionary for the desired value. If the value is absent, the corresponding dictionary is removed from the original list

Python
a = [{'a': 1}, {'b': 2}, {'c': 3, 'd': 4}, {'e': 5}]

# Remove dictionaries without the value 3
for d in a[:]:  # Iterate over a copy of the list
    if 3 not in d.values():
        a.remove(d)
print(a) 

Output
[{'c': 3, 'd': 4}]

Explanation:

  • for loop iterates over a copy of the list a (a[:]) to avoid modifying the list while iterating, checking if the value 3 is not in the dictionary's values.
  • Dictionaries that do not contain the value 3 are removed using the remove() method, resulting in a = [{'c': 3, 'd': 4}]

Similar Reads