I am trying to delete a key form a multi-level dictionary. My code to create the dictionary is below:
from collections import defaultdict
f = lambda: defaultdict(f)
d = f()
d['A']['B1']['C1'] = 1
d['A']['B1']['C2'] = 2
d['A']['B1']['C3'] = 3
d['A']['B2']['C1'] = 15
d['A']['B2']['C2'] = 20
Now I am trying to delete 'C3' key. The final structure for the dictionary is :
{
"A": {
"B1": {
"C1": 1,
"C2": 2
},
"B2": {
"C1": 15,
"C2": 20
}
}
}
My try :
for level_1_key, level_1_dct in d.items():
for level_2_key, level_2_dct in level_1_dct.items():
for level_3_key, level_value in level_2_dct.items():
if level_value == 3:
d[level_1_key][level_2_key].pop(level_3_key, 'None')
and I am getting the below error while running the above code:
RuntimeError: dictionary changed size during iteration
So can anyone please help me to fix and understand the issue.