user1022585 user1022585 -3 years ago 87
Python Question

dict changed size during iteration, but not editing it in Python

I'm getting the

dict changed size during iteration
error in Python even though I'm not altering the nested dict. I'm deleting from the original, not the copy that I'm looping through

test = arr.copy()
for map in test:
for mID in test[map]: #here is dictionary changed size during iteration
v = test[map][mID]['val']
if v < 1:
del arr[map][mID]

Am I overlooking something?

Answer Source

you're copying the dictionary but using shallow copy.

Since you're iterating on a sub-dict (which isn't copied, the reference is the same between arr and test), you get this error.

Use the deepcopy function of the copy module like this:

import copy
test = copy.deepcopy(arr)

However, deep-copying an object is overkill for such a problem. You could just iterate on a copy of the items like this (also: always iterate on key+values so you don't have to access the value by key within the loop):

for map,map_values in arr.items():
    for mID,subdict in list(map_values.items()):  # make a copy/force iteration using `list`
        v = subdict['val']
        if v < 1:
            del map_values[mID]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download