vanipel
vanipel

Reputation: 55

How to delete an item from json while iterating it?

I cannot delete items from json while iterating it. I've tried several ways to achieve it, but it's not working as expected.

There is json example:

{
    "year" : 2019,
    "values" : [{
            "key" : 70,
            "messages" : [{
                    "code" : 997,
                    "messages" : 1112245
                }
            ]
        }, {
            "key" : 90,
            "messages" : [{
                    "code" : 997,
                    "messages" : 26347680
                }
            ]
        }
]}

I need to iterate "values" and delete the items with specific "key". There is a separate list of keys:

key_list = [60, 70, 80, 90]

I tried to use following code, but it doesn't work:

for i in json["values"]:
        if i["key"] not in key_list :
            del i 

I also tried to use pop, popitem, clear without effect.

The current version is:

def delRecords(json):
    x = 0
    for i in json["values"]:
        if i["key"] not in key_list :
            json["mtids"].pop(x)
        x += 1
    return json

But it looks ugly and I have to start the script several times to delete all items. Could you please give an advice how can I delete the items from the json? Is there any best practice for it?

Thanks!

Upvotes: 2

Views: 254

Answers (1)

cs95
cs95

Reputation: 403278

No hackery is needed if you iterate in reverse and delete:

key_set = {60, 70, 80, 90}  
values = jsonData['values'] # hold reference, less typing  

for i in reversed(range(len(values))):
    if values[i]['key'] not in key_list:
        del values[i]

Or, you may use a list comprehension to re-create the list if your data is reasonably sized:

jsonData['values'] = [d for d in jsonData['values'] if d['key'] in key_set]

PS, use a set when checking for keys because set lookup is constant time.

Upvotes: 4

Related Questions