-1

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.

Arijit Panda
  • 1,581
  • 2
  • 17
  • 36

1 Answers1

0

The error message tells you exactly what the problem is. You're trying to remove the item while you're still iterating over the dictionary which is not possible in python. Instead, you should keep a reference to the item's path and delete it after you're done iterating:

paths = []
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:
                paths.append((level_1_key, level_2_key, level_3_key))

for lvl1, lvl2, lvl3 in paths:
    d[lvl1][lvl2].pop(lvl3, None)
mgilson
  • 300,191
  • 65
  • 633
  • 696