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 SummaryIn 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
…