How to avoid "RuntimeError: dictionary changed size during iteration" error?

Suppose I have a dictionary of lists:

d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}

Now I want to remove key-value pairs where the values are empty lists. I tried this code:

for i in d:
    if not d[i]:
        d.pop(i)

but this gives an error:

RuntimeError: dictionary changed size during iteration

I understand that entries can't be added or removed from a dictionary while iterating through it. How can I work around this limitation in order to solve the problem?


See Modifying a Python dict while iterating over it for citations that this can cause problems, and why.

← Назад к списку