0

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!

Dhruv Kaushal
  • 201
  • 2
  • 12
  • where's x? show your error – Zabir Al Nazi Apr 02 '20 at 05:42
  • We have only guesses as to where you're going wrong, since you failed to provide the expected [MRE](https://stackoverflow.com/help/minimal-reproducible-example). It depends on the mutability of `row`. Note that you have *not* applied the deletion to `data`. – Prune Apr 02 '20 at 05:43
  • There is no error. It's just that the row is not being deleted. Also, x is a set of numbers. I'll edit my question to show it. – Dhruv Kaushal Apr 02 '20 at 05:43
  • Umm...I'm a bit new to stackoverflow, and unaware of how things work here. Can someone please help me understand why my question was downvoted? Was it because of lack of clarity or something else? Just curious. – Dhruv Kaushal Apr 02 '20 at 05:48

1 Answers1

5

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.

user2390182
  • 72,016
  • 6
  • 67
  • 89