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:
JavaScript
x
26
26
1
{
2
"_notes": [
3
{
4
"_time": 10,
5
"_lineIndex": 2,
6
"_lineLayer": 0,
7
"_type": 0,
8
"_cutDirection": 7
9
},
10
{
11
"_time": 12,
12
"_lineIndex": 2,
13
"_lineLayer": 0,
14
"_type": 1,
15
"_cutDirection": 1
16
},
17
{
18
"_time": 14,
19
"_lineIndex": 2,
20
"_lineLayer": 1,
21
"_type": 1,
22
"_cutDirection": 0
23
}
24
]
25
}
26
My python script:
JavaScript
1
14
14
1
#!/usr/bin/python3
2
3
import json
4
obj = json.load(open("ExpertPlusStandardd.dat"))
5
6
for i in range(len(obj["_notes"])):
7
print(obj["_notes"][i]["_type"])
8
if obj["_notes"][i]["_type"] == 1:
9
obj.pop(obj["_notes"][i])
10
11
open("test.dat", "w").write(
12
json.dumps(obj, indent=4, separators=(',', ': '))
13
)
14
Error:
Traceback (most recent call last): File "C:programmingpythontrain_one_handrun.py", line 9, in <module> obj.pop(obj["_notes"][i]) TypeError: unhashable type: 'dict'
Advertisement
Answer
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.
JavaScript
1
2
1
obj["_notes"] = [x for x in obj["_notes"] if x["_type"] != 1]
2
This gives us the expected output :
JavaScript
1
12
12
1
{'_notes':
2
[
3
{
4
'_time': 10,
5
'_lineIndex': 2,
6
'_lineLayer': 0,
7
'_type': 0,
8
'_cutDirection': 7
9
}
10
]
11
}
12