Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, delete JSON element having specific key from a loop

Using Python, I need to delete all objects in JSON array that have specific value of 'name' key. However, I can't do that from a loop.

Imaging I want to delete all items having 'bad' as name in the following input:

{
  'myArray' : [
    {
      'name' : 'good',
      'value' : '1'
    },
    {
      'name' : 'bad',
      'value' : '2'
    }
  ]
}

So I use the following Python test case:

myData = {'myArray': [{'name': 'good', 'value': '1'}, {'name': 'bad', 'value': '2'}]}

for a in myData['myArray']:
  if (a['name'] =='bad'):
    del a

print(json.dumps(myData))

And I see that the myData is not changed.

I assume this is because I try to delete an iterator of a loop, that might be considered as risky action by interpreter, however no runtime error or warning is reported by Python.

What's the recommended approach in this case?

Thanks!

like image 586
Dmytro Avatar asked Oct 17 '22 13:10

Dmytro


2 Answers

One of approaches from Remove element from list when using enumerate() in python - a loop over a copy of the list referred as [:] - works too:

for a in myData['myArray'][:]:
  if (a['name'] == u'bad'):
     myData['myArray'].remove(a)

Thanks everyone!

like image 123
Dmytro Avatar answered Oct 21 '22 02:10

Dmytro


Use a (nested) dict/list comprehension. Never try to delete elements of an object while iterating over it

>>> [x for x in myData['myArray'] if x['name'] != 'bad']
[{'name': 'good', 'value': '1'}]

Assign the result to myData['myArray'], or whatever you want.

like image 42
smci Avatar answered Oct 21 '22 03:10

smci