Modifying a dictionary while iterating over it
- iteration
- dict
You cannot modify the dictionary you are currently iterating over. Attempting to do that causes Python to throw an error:
dictionary keys changed during iteration
You can work around this by copying the dictionary’s keys to a separate list, and iterating over that instead, or by deferring the changes to after the loop, e.g. by collecting the changes to be performed into a separate list and then modifying the dictionary after looping over it.