About Avoiding the Error of Changed Dictionary Size During Iteration

To avoid runtime errors of dictionary changing size during iteration when you need to add or remove values in a loop, make a copy at first:

1
2
3
4
5
6
7
from copy import deepcopy

d = {"a": "A", "b": "B", "c": "C"}

for key in deepcopy(d):
    if not should_keep(key):
        d.pop(key, None)

Tips and Tricks Programming Python 3