PyCodeItPython trace & interview prep
python

Python Dictionary Iteration Order and Pitfalls

Insertion order, views, and runtime mutations in common dry-run themes.

AA

Ameer Abdullah

Data Science & AI/ML Graduate-GitHub-Dev.to

5 min read

Concept in Simple Words: In Python 3.7+, dictionaries preserve insertion order. However, iterating over a dictionary and mutating it (adding or deleting keys) at the same time is not allowed. Python will raise an error because the dictionary size changes during iteration.

Deep Walkthrough & Code: Let's look at a function that attempts to prune a dictionary based on threshold values:

def prune_dict(d, threshold):
    for key, value in d.items():
        if value < threshold:
            del d[key]  # Bug: mutating dictionary size
    return d
Step-by-Step Dry Run: Let's trace prune_dict({'a': 1, 'b': 5}, 3):
- Loop starts iterating over d.items().
- First item: key='a', value=1. 1 < 3 is True. We delete d['a'].
- Python immediately raises a RuntimeError: 'dictionary changed size during iteration'. The iteration is interrupted.
Production Level Issue & Fix: To safely delete items during iteration in production, iterate over a copy of the keys rather than the dict views directly: `for key in list(d.keys()):
    if d[key] < threshold:
        del d[key]`.

Practice what you just learned

Apply these concepts in PyCodeIt's interactive sandbox with real problems.

Start Python Practice

Related Python Tutorials