How to Avoid \'RuntimeError: dictionary changed size during iteration\'?

Mary-Kate Olsen
Release: 2024-11-04 10:01:30
Original
272 people have browsed it

How to Avoid

Avoiding "RuntimeError: dictionary changed size during iteration"

When attempting to modify a dictionary while iterating through it, you may encounter the "RuntimeError: dictionary changed size during iteration" error. This arises because modifying the dictionary's size (adding or removing entries) while looping over it invalidates the iterator.

To address this issue, the recommended approach is to create a copy of the dictionary keys using list() or iterate over the keys via d.keys(). For Python 3.x, d.keys() returns a view object, requiring you to create an explicit copy using list().

For example, consider the following dictionary:

<code class="python">d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}</code>
Copy after login

To remove key-value pairs with empty lists, you can use the following code:

<code class="python">for i in list(d):  # Python 3.x
# or
for i in d.keys():  # Python 2.x
    if not d[i]:
        d.pop(i)</code>
Copy after login

By creating a copy of the keys using list(), we avoid the issue of modifying the dictionary size during iteration and ensure that the loop completes successfully.

The above is the detailed content of How to Avoid \'RuntimeError: dictionary changed size during iteration\'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!