All Python errors
RuntimeError: dictionary changed size during iteration
This message means keys were added to or removed from a dictionary while a for loop was walking through it. To fix it, loop over a copy of the keys, for key in list(d), or build a new dictionary.
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)
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: DictionariesFrequently 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.