Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i delete an element of a json object with python?

I’m trying to delete elements from _notes that have _type as 1, but i keep getting an error and I’m not sure what it means, nor do I know how to fix it.. can anyone help me?

My trimmed JSON:

{
    "_notes": [
        {
            "_time": 10,
            "_lineIndex": 2,
            "_lineLayer": 0,
            "_type": 0,
            "_cutDirection": 7
        },
        {
            "_time": 12,
            "_lineIndex": 2,
            "_lineLayer": 0,
            "_type": 1,
            "_cutDirection": 1
        },
        {
            "_time": 14,
            "_lineIndex": 2,
            "_lineLayer": 1,
            "_type": 1,
            "_cutDirection": 0
        }
    ]
}

My python script:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/usr/bin/python3

import json
obj = json.load(open("ExpertPlusStandardd.dat"))

for i in range(len(obj["_notes"])):
    print(obj["_notes"][i]["_type"])
    if obj["_notes"][i]["_type"] == 1:
        obj.pop(obj["_notes"][i])

open("test.dat", "w").write(
    json.dumps(obj, indent=4, separators=(',', ': '))
)

Error:
Traceback (most recent call last): File "C:\programming\python\train_one_hand\run.py", line 9, in <module> obj.pop(obj["_notes"][i]) TypeError: unhashable type: 'dict'

>Solution :

It is usually a bad idea to delete from a list that you’re iterating. Reverse iterating avoids some of the pitfalls, but it is much more difficult to follow code that does that, so usually you’re better off using a list comprehension or filter.

obj["_notes"] = [x for x in obj["_notes"] if x["_type"] != 1]

This gives us the expected output :

{'_notes': 
   [
       {
            '_time': 10, 
            '_lineIndex': 2, 
            '_lineLayer': 0, 
            '_type': 0, 
            '_cutDirection': 7
       }
   ]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading