RuntimeError dict 🐍 Python

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

  1. Iterate over list(d) or list(d.items())
  2. Build a new dict with a comprehension
  3. Collect keys to delete, then delete after the loop

Detailed fix by platform

Python

  1. active = {k: v for k, v in users.items() if v.active}

How to diagnose

  1. Loop — Which loop mutates the dict?
  2. 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.