I have a python script which read a .json file and iterate trough a dictionary with the purpose of changing its "format", i knew that deleting elements from a dict while in a for loop would raise an error, so i created a copy of the original and called .pop() fn on it. here's the code:
import json
with open('betway/betway.json', 'r') as f:
con = json.loads(f.read())['connection']
new_con = con
for s in con:
for c in con[s]:
for t in con[s][c]:
new_con[s][c]['sf'] = con[s][c][t]['sf-c']
new_con[s][c][t]['sf'] = con[s][c][t]['sf-t']
for team in con[s][c][t]['teams']:
new_con[s][c][t][team] = con[s][c][t]['teams'][team]
new_con[s][c][t].pop('sf-t')
new_con[s][c][t].pop('sf-c')
new_con[s][c][t].pop('teams')
with open('betway/connection.json', 'w') as f:
f.write(json.dumps(new_con, indent=2))
but after doing so it still raised the same RuntimeError error:
Traceback (most recent call last):
File "/home/hypnos/Documents/arbitrage/betway/x.py", line 10, in <module>
for t in con[s][c]:
RuntimeError: dictionary changed size during iteration
I found a solution to this error changing for t in con[s][c]:
to for t in list(con[s][c]):
I know that list() create a fixed list of the keys in the dict but my question is, since already in the first version there weren't no changes done to the "con" dictionary what is exactly causing the error to raise?