Categories
Python Answers

How to avoid “RuntimeError: dictionary changed size during iteration” error with Python?

Spread the love

Sometimes, we want to avoid "RuntimeError: dictionary changed size during iteration" error with Python.

In this article, we’ll look at how to avoid "RuntimeError: dictionary changed size during iteration" error with Python.

How to avoid "RuntimeError: dictionary changed size during iteration" error with Python?

To avoid "RuntimeError: dictionary changed size during iteration" error with Python, we’ve to make a copy of the dict before we can modify the original in a loop.

For instance, we write

for i in list(d):
    # ...

to call list with dict d to make a copy of d and get the keys from the copied dict.

Conclusion

To avoid "RuntimeError: dictionary changed size during iteration" error with Python, we’ve to make a copy of the dict before we can modify the original in a loop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *