. Advertisement .
..3..
. Advertisement .
..4..
You remember not changing your dictionary even just once. And yet, upon the code printing, the system sends back a RuntimeError “Dictionary changed size during iteration.”
What is happening here? How can you tackle this error? Check out ITtutoria guidelines for examples.
Why Does It Happen?
Python usually requires a looping operation over lists instead of dicts. Still, that does not mean there are no exceptions. Some instances call for dictionary looping.
Nevertheless, upon dictionary modifications during this looping task, you will likely get an exception. Why? It’s because Python interpreters might take note of the element quantity within the dict during your loop setup. So once the dictionaries change, it will throw off everything.
This example will illustrate what it’s like when the error occurs:
Example 0 (Code):
foo = {'a': 1, 'b': 2, 'c': 3}
for key in foo:
print(f"{key}: {foo[key]}")
if key == 'c':
foo['d'] = 4
The code boasts a basic dictionary named “foo”, featuring three keys with three values. Nothing is problematic so far, right?
Look closer! We have added a fourth key to “foo” once we reach the “c” keys, which has altered the key quantity from the dictionary. Python will likely not accommodate this sudden chance. Hence, unsurprisingly, we end up with the error below:
Example 0 (Error):
a: 1
b: 2
c: 3
Traceback (most recent call last):
File "/home/user/main.py", line 3, in <module>
for key in foo:
RuntimeError: dictionary changed size during iteration
Whoops! How should we fix this mistake? Let’s get on to our next section.
How To Fix The RuntimeError “Dictionary Changed Size During Iteration”
One good method is to use the Key() function from Python dict types to obtain objects that contain all the keys present when this method operates. In simpler terms, it will give you copies of the keys.
And here lies the secret: it will return a class instance called “dict_key” (instead of actual lists). That’s why, in this second attempt:
Example 0 (Error) (cont):
foo = {'a': 1, 'b': 2, 'c': 3}
for key in foo.keys(): # ❌ This won't work!
print(f"{key}: {foo[key]}")
if key == 'c':
foo['d'] = 4
The error still occurs. Why? Because your “dict_keys” object contains references to “foo’s” keys, which also changes once you modify the foo. Thus, it will be better to make key copies by throwing them onto this list:
Example 0 (Solution):
foo = {'a': 1, 'b': 2, 'c': 3}
for key in list(foo.keys()): # ✅ This will work!
print(f"{key}: {foo[key]}")
if key == 'c':
foo['d'] = 4
# -> a: 1
# b: 2
# c: 3
This code will help generate copies of the keys (at the moment you cast them onto a list). You may do whatever you wish with “foo” in this loop.
Conclusion
This article has provided a clear example of how to fix the RuntimeError “Dictionary changed size during iteration.”
For similar RuntimeError on Python (such as cuDNN error: CUDNN_STATUS_NOT_INITIALIZED), feel free to browse through ITtutoria guidelines for more support, examples, and tips!
Leave a comment