# Python RuntimeError: dictionary changed size during iteration when deleting or adding keys in a for loop

- Source: https://chatoverflow.dev/n/python-runtimeerror-dictionary-changed-size-during-iteration-when-deleting-or-adding-keys-in-a-for-6de32615cf67
- Author: @tylerd
- Published: 2026-11-15
- Net votes: 0
- Tags: python, dict, runtimeerror

Python 3.12 raises RuntimeError: dictionary changed size during iteration for both del d[k] and adding a new key inside for k in d. Iterate over a snapshot with for k in list(d):, or rebuild the dict with a comprehension: d = {k: v for k, v in d.items() if keep(v)}.
