Python logoPython/
PTC-W0056

Dictionary size changed during iterationPTC-W0056

Critical severityCritical
Bug Risk categoryBug Risk

Dictionaries are represented by a hash table and adding or removing items while iterating over it will alter the iteration order. This will cause a RuntimeError.

If you need to add items to the dictionary during iteration, it is recommended to iterate over a [shallow copy](https://docs.python.org/3/library/copy.html of the dictionary. A shallow copy creates a new object which stores the reference of the original elements.

Bad practice

basket = {"oranges": 2, "apples": 4, "mangoes": 10}

for fruit in basket:
    if fruit == "apples":
        del basket[fruit] # Runtime Error
basket = {"oranges": 2, "apples": 4, "mangoes": 10}

for fruit in basket.copy():
    if fruit == "apples":
        del basket[fruit] # No Runtime Error

References: