Why This Happens
Python dicts cannot be modified during iteration. Adding or removing keys invalidates the iterator. The same applies to sets.
The Problem
data = {'a': 1, 'b': 2, 'c': 3}
for key in data:
if data[key] < 2:
del data[key]The Fix
data = {'a': 1, 'b': 2, 'c': 3}
for key in list(data.keys()):
if data[key] < 2:
del data[key]
# Or dict comprehension:
data = {k: v for k, v in data.items() if v >= 2}Step-by-Step Fix
- 1
Copy keys first
Use list(dict.keys()) to create a copy.
- 2
Use comprehension
Create a new filtered dict.
- 3
Collect changes separately
Build a list of keys to remove, apply after loop.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free