Dhruv Kaushal
Dhruv Kaushal

Reputation: 211

Deleting a dictionary from a list of dictionaries

I am trying to delete a dictionary from a list of dictionaries, but unable to achieve it. Here's what I've tried so far:

x = set()         
for row in comment_data['data']:
    x.add(row['RUNID'])
for row in data['data']:
    if row['ID'] not in x:
        del row

Here data['data'] is a list of dictionaries. x is a set of numbers, I fetch from comment_data. I want to delete the dictionary if row['id'] is not in x. How do I acieve this? Where am I going wrong? I tried the answers given on this link, but none of them seem to work for me. Any help is appreciated!

Upvotes: 0

Views: 327

Answers (1)

user2390182
user2390182

Reputation: 73498

You should not try to modify a list's structure while iterating over it. Also, del row just removes the binding of the loop variable row which does not affect the list. Do instead:

data['data'] = [row for row in data['data'] if row['ID'] in x]

Note that despite (because of) creating a new list object, this has also better algorithmic performance than your initial attempt as it is linear while repeated removal from the middle of a list is quadratic as the tail elements have to be shifted each time.

Upvotes: 5

Related Questions