1

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:

#!/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'

6
  • 2
    always put full error message (starting at word "Traceback") in question (not in comments) as text (not screenshot, not link to external portal). There are other useful information. Commented Jul 17, 2022 at 14:15
  • as for me this JSON data can't give your error message - you have to check what you really have in your file "ExpertPlusStandardd.dat" Commented Jul 17, 2022 at 14:16
  • edited the error message Commented Jul 17, 2022 at 14:16
  • i copied the contents of ExpertPlusStandardd.dat into my question Commented Jul 17, 2022 at 14:17
  • it is wrong idea to remove (pop) item from object which you use in for-loop - because it moves items on list and later it tries to use index which doesn't exists any more. You should rather create new JSON and put in this JSON elements which you want to keep Commented Jul 17, 2022 at 14:20

1 Answer 1

2

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
       }
   ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.