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.
In Python 3.x and 2.x you can use use
listto force a copy of the keys to be made:In Python 2.x calling
.keysmade a copy of the keys that you could iterate over while modifying thedict:but on Python 3.x,
.keysreturns a view object instead, so it won’t fix your error.