Python Defaultdicts and Dictionary Size Changed Error
I had a python script that was using a defaultdict to store some values and then passed it in to a function along with a string, to do some further processing. Within the function there was a for loop to iterate over the dictionary for further processing.
During the run, I kept on getting this error
RuntimeError: dictionary changed size during iteration
This was odd since I wasnt adding or deleting any values in the function and was only going over it with a for loop like this:
for key, val in map_ids:
#do something
Turns out that a default value is created when iterating over a defaultdict causing a size change error. The easiest way to solve this is to get a list of the items that returns the dictionary view, thereby iterating over that list instead of the defaultdict
for key, val in map_ids.items():
#do something