RuntimeError: dictionary changed size during iteration
A dict (or set) was modified while being looped over.
Seen on:
Python
Meaning
Adding or deleting keys during iteration invalidates the iterator. Iterate over a copy of the keys, or build a new dict.
Common causes
- del d[k] inside for k in d
- Adding keys while iterating
- Another thread mutating the dict
⚡ Quick fix
- Iterate over list(d) or list(d.items())
- Build a new dict with a comprehension
- Collect keys to delete, then delete after the loop
Detailed fix by platform
Python
active = {k: v for k, v in users.items() if v.active}
How to diagnose
- Loop — Which loop mutates the dict?
- Threads — Is another thread writing to it?
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 2 Oct 2026