Avatar ·

How to remove an item from a dictionary during a for loop

📁 Advanced Python Topics, Error, example

I somehow suddenly ran into such a problem. During a for loop, I need to remove entries from it, but how can I avoid the error:

RuntimeError: dictionary changed size during iteration

I even tried to make a snapshot of the dictionary before iteration and iterate over the copy while removing from the original.

>>> d = {12: 'wqe', 13: 'wqe', 14: 'wqe', 15: ''}