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.
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 value3is present ind.values(). - Resulting list
fis 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.
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 listd, checking if the value3exists ind.values(), and retains those that satisfy the condition.- Filtered result is converted to a list
fand printed, resulting inf = [{'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
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:
forloop iterates over a copy of the lista(a[:]) to avoid modifying the list while iterating, checking if the value3is not in the dictionary's values.- Dictionaries that do not contain the value
3are removed using theremove()method, resulting ina = [{'c': 3, 'd': 4}]