Avatar ·

How to delete a value from a dictionary during a for loop

📁 Advanced Python Topics, Error, example

Somehow unexpectedly encountered this problem. During a for loop over a dictionary, I need to delete entries from it, but no matter what I do, I get an error:

RuntimeError: dictionary changed size during iteration

I even tried taking a snapshot of the dictionary before iteration and iterating over the copy while deleting from the original.

Example:

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