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

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    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:
    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.

    Continue reading...

Compartilhe esta Página