'remove specific dictionaries in a list Python [closed]
I have a list of dictionaries:
persons = [{'id': 1, 'name': 'john'},
{'id': 2, 'name': 'doe'},
{'id': 3, 'name': 'paul'}]
ids = [1,3]
# remove_persons(persons, ids) --> [{'id': 2, 'name': 'doe'}]
I would like to remove dictionaries from a list of id.
What is the most efficient way to go about this programmatically.
Solution 1:[1]
This will work for you:
- function to delete specific id:
def remove_person(persons, person_id):
return [person for person in persons if person['id'] != person_id]
ids_to_delete = [1,3]
for id in ids_to_delete:
persons = remove_person(persons, id)
#output
persons
[{'id': 2, 'name': 'doe'}]
- not a function:
persons = [{'id': 1, 'name': 'john'},
{'id': 2, 'name': 'doe'},
{'id': 3, 'name': 'paul'}]
ids = [1, 3]
persons = [person for person in persons if person['id'] not in ids]
Solution 2:[2]
You can use an index for popping out elements.
for i in ids:
persons.pop(i-1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Haider Ali |
