Search code examples
pythonlistdictionaryloops

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.


Solution

  • In Python 3.x and 2.x you can use use list to force a copy of the keys to be made:

    for i in list(d):
    

    In Python 2.x calling .keys made a copy of the keys that you could iterate over while modifying the dict:

    for i in d.keys():
    

    but on Python 3.x, .keys returns a view object instead, so it won't fix your error.