DanH
DanH

Reputation: 5818

Remove items from list of dicts with a matching attribute

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

Answers (3)

Silas Ray
Silas Ray

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

eumiro
eumiro

Reputation: 213075

data = [d for d in data if d['id'] not in remove_ids]

Upvotes: 2

namit
namit

Reputation: 6957

new_data=[x for x in data if x['id'] not in remove_ids]

Upvotes: 2

Related Questions