Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Remove dictionary from a list of dictionaries if a particular value is not present
When you need to remove a dictionary from a list based on whether a particular value is present or absent, you can use several approaches. The most common methods are iteration with del, list comprehension, or the filter() function.
Method 1: Using del with Index-based Iteration
This method iterates through the list and removes the dictionary when a condition is met ?
my_list = [{"id": 1, "data": "Python"},
{"id": 2, "data": "Code"},
{"id": 3, "data": "Learn"}]
print("The list is:")
print(my_list)
for index in range(len(my_list)):
if my_list[index]['id'] == 2:
del my_list[index]
break
print("The result is:")
print(my_list)
The list is:
[{'id': 1, 'data': 'Python'}, {'id': 2, 'data': 'Code'}, {'id': 3, 'data': 'Learn'}]
The result is:
[{'id': 1, 'data': 'Python'}, {'id': 3, 'data': 'Learn'}]
Method 2: Using List Comprehension
List comprehension provides a more Pythonic way to filter dictionaries ?
my_list = [{"id": 1, "data": "Python"},
{"id": 2, "data": "Code"},
{"id": 3, "data": "Learn"}]
print("The original list is:")
print(my_list)
# Remove dictionaries where id is 2
filtered_list = [d for d in my_list if d['id'] != 2]
print("The filtered list is:")
print(filtered_list)
The original list is:
[{'id': 1, 'data': 'Python'}, {'id': 2, 'data': 'Code'}, {'id': 3, 'data': 'Learn'}]
The filtered list is:
[{'id': 1, 'data': 'Python'}, {'id': 3, 'data': 'Learn'}]
Method 3: Using filter() Function
The filter() function provides another clean approach ?
my_list = [{"id": 1, "data": "Python"},
{"id": 2, "data": "Code"},
{"id": 3, "data": "Learn"}]
print("The original list is:")
print(my_list)
# Remove dictionaries where id is 2
filtered_list = list(filter(lambda d: d['id'] != 2, my_list))
print("The filtered list is:")
print(filtered_list)
The original list is:
[{'id': 1, 'data': 'Python'}, {'id': 2, 'data': 'Code'}, {'id': 3, 'data': 'Learn'}]
The filtered list is:
[{'id': 1, 'data': 'Python'}, {'id': 3, 'data': 'Learn'}]
Comparison
| Method | Modifies Original | Readability | Best For |
|---|---|---|---|
del with loop |
Yes | Good | Removing single item |
| List comprehension | No | Excellent | Multiple conditions |
filter() |
No | Good | Complex filtering logic |
Key Points
When using
del, always includebreakto avoid index errorsList comprehension creates a new list and doesn't modify the original
The
filter()function returns an iterator that needs conversion to listChoose the method based on whether you need to modify the original list
Conclusion
Use list comprehension for readable filtering of dictionaries. Use del when you need to modify the original list in place. The filter() function works well for complex conditional logic.
