students = [
{'id': 1, 'name': 'Richard'},
{'id': 2, 'name': 'Jared'},
{'id': 3, 'name': 'Dinesh'}
]
for index, item in enumerate(students):
if item['id'] == 2:
del students[index]
print(students)
We are using Python For loop and enumerate() function to remove a dictionary from the list based on key 'id' value.
Here is another code example to create a new list after removing a dictionary based on some conditions. We are using Python filter() and lambda function to do that.
Code Example
students = [
{'id': 1, 'name': 'Richard'},
{'id': 2, 'name': 'Jared'},
{'id': 3, 'name': 'Dinesh'}
]
result = list(filter(lambda item: item['id'] != 2, students))
print(result)
Output
[{'id': 1, 'name': 'Richard'}, {'id': 3, 'name': 'Dinesh'}]
We can also use List Comprehension to remove some dictionary items from the list and get a new list with filtered dictionary items.
Code Example
students = [
{'id': 1, 'name': 'Richard'},
{'id': 2, 'name': 'Jared'},
{'id': 3, 'name': 'Dinesh'}
]
result = [item for item in students if not (item['id'] == 2)]
print(result)
Output
[{'id': 1, 'name': 'Richard'}, {'id': 3, 'name': 'Dinesh'}]
0 Comments