Code with the error

stock = {"apples": 0, "pears": 4}
for fruit in stock:
    if stock[fruit] == 0:
        del stock[fruit]
print(stock)

Error message (Python 3.12, last line)

RuntimeError: dictionary changed size during iteration

Corrected code

stock = {"apples": 0, "pears": 4}
for fruit in list(stock):
    if stock[fruit] == 0:
        del stock[fruit]
print(stock)

Output

{'pears': 4}

Common causes

  • del removes a key inside a loop over the same dictionary.
  • A new key is added inside the loop.
  • pop() is called on the dictionary being looped over.
  • A function called from the loop changes the same dictionary.

Practise in the course

Lesson: Dictionaries

Frequently asked questions

May I change values inside the loop?

Yes. Replacing the value of an existing key keeps the size the same.

Why does list(d) help?

It makes a separate list of the keys, so the loop no longer depends on the dictionary being changed.