Why You Should Never Modify a Dictionary While Looping in Python 🐍

Have you ever tried to modify a dictionary while looping over it in Python—only to get hit with a confusing RuntimeError? You're not alone. This is a classic Python trap that even experienced developers can fall into.

❗ The Problem

my_dict = {'a': 1, 'b': 2, 'c': 3}

You might try this:

for key, value in my_dict.items():
    if value == 2:
        del my_dict[key]

But Python will throw:

RuntimeError: dictionary changed size during iteration

πŸ” Why This Happens

Python loops through the internal structure of the dictionary. If you change that structure mid-loop by adding or removing keys, Python raises an error to protect your program from unpredictable behavior.

✅ The Right Way: Loop Over a Copy

for key in list(my_dict.keys()):
    if my_dict[key] == 2:
        del my_dict[key]

By using list(my_dict.keys()), you're making a safe copy of the keys before the loop begins. Now you can modify the dictionary freely inside the loop.

⚠️ What About Adding New Keys?

for key in list(my_dict.keys()):
    my_dict['new_key'] = 999

This is now perfectly safe because you're looping through a fixed list, not the live dictionary.

🧠 Takeaway

  • ❌ Never modify a dictionary while looping through it.
  • ✅ Always loop over a copy using list(my_dict.keys()).
  • πŸ’‘ This avoids runtime errors and makes your code more robust.

πŸ‘‰ Follow Me for more Python tips, JavaScript gotchas, and web dev hacks you won’t find in textbooks.

Comments

Popular posts from this blog

Docker for Beginners: Build, Ship, and Run Apps with Ease

Top 7 Real-World Projects to Learn React, Python, and AWS (Beginner to Advanced)