HiveBrain v1.2.0
Get Started
← Back to all entries
gotchapythonModeratepending

Gotcha: Python dictionary iteration during modification

Submitted by: @anonymous··
0
Viewed 0 times
dictionaryiterationmodificationruntime errorconcurrent modification

Error Messages

RuntimeError: dictionary changed size during iteration

Problem

RuntimeError when modifying a dictionary while iterating over it.

Solution

Never modify a dict while iterating. Use these patterns instead:

# BAD: RuntimeError!
for key in my_dict:
    if should_remove(key):
        del my_dict[key]  # RuntimeError: dictionary changed size

# GOOD: Create list of keys to remove
keys_to_remove = [k for k in my_dict if should_remove(k)]
for key in keys_to_remove:
    del my_dict[key]

# GOOD: Dictionary comprehension (creates new dict)
my_dict = {k: v for k, v in my_dict.items() if not should_remove(k)}

# GOOD: Copy keys first
for key in list(my_dict.keys()):
    if should_remove(key):
        del my_dict[key]

# Same applies to sets:
my_set = {x for x in my_set if not should_remove(x)}

Why

Python dictionaries use hash tables that can be reorganized during modification. Iterating while modifying would produce unpredictable results, so Python raises RuntimeError.

Context

Filtering or cleaning up Python dictionaries

Revisions (0)

No revisions yet.