Reputation: 5818
I have a list of dicts for instance:
data = [
{ 'id': 1 },
{ 'id': 2 },
{ 'id': 3 },
{ 'id': 4 },
{ 'id': 5 },
]
remove_ids = [3,4]
So I'd like to apply remove_ids
to list
and end up with only:
list = [
{ 'id': 1 },
{ 'id': 2 },
{ 'id': 5 },
]
I was thinking something along the lines of:
data.remove([item (if item['id'] in remove_ids) for k, item in data])
Obviously this doesn't work, but I'm interested to know whether I was even close. I was also interested to see if this is even possibly in a single line.
Upvotes: 0
Views: 113
Reputation: 26160
You could use filter
.
remove_ids = (3, 4)
filtered_data = filter(lambda item: item['id'] not in remove_ids, data)
If data
is large or you do this very frequently, you might also get benefit out of itertools
.
from itertools import ifilterfalse
remove_ids = (3, 4)
filtered_data = tuple(ifilterfalse(lambda item: item['id'] in remove_ids, data))
Upvotes: 2