Why Python Dictionaries Crash When You Add or Delete Keys While Looping
Here is a situation that is easy to run into: you have a dictionary of scores and one simple job, remove everyone below 50. Four lines of code, nothing fancy. Python answers with this:
RuntimeError: dictionary changed size during iteration
Try the same pattern on a list and it doesn't crash at all. It quietly gives you the wrong answer. So why does the dictionary version scream while the list version stays silent?
Quick Summary
- In CPython, adding or removing keys while looping over a dictionary raises RuntimeError on the next step of the loop.
- The crash can happen after the dictionary has already been partly modified, so you can be left with half-updated data.
- A list iterator can keep going after the list changes, which can cause elements to be skipped. A dictionary iterator detects the change and raises an error.
- Three safe fixes: loop over a snapshot of...
Copyright of this story solely belongs to hackernoon.com. To see the full text click HERE