Home  >  Article  >  Backend Development  >  How to Avoid the \"RuntimeError: dictionary changed size during iteration\" in Python?

How to Avoid the \"RuntimeError: dictionary changed size during iteration\" in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 18:59:02299browse

How to Avoid the

Avoiding the "RuntimeError: dictionary changed size during iteration" Error

Attempting to modify a dictionary while iterating over it, as seen in the code snippet below, can trigger the "RuntimeError: dictionary changed size during iteration" error:

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

for i in d:
    if not d[i]:
        d.pop(i)</code>

To overcome this limitation, various approaches can be employed:

Python 2.x and 3.x:

Force a copy of the keys using 'list':

<code class="python">for i in list(d):</code>

Python 3.x (and later):

Use 'collections.OrderedDict':

<code class="python">from collections import OrderedDict

for i in OrderedDict(d):</code>

Alternative Solutions:

  1. Create a new dictionary with the desired modifications:
<code class="python">new_d = {}
for key, value in d.items():
    if value:
        new_d[key] = value</code>
  1. Use Python 3.3' s 'popitem' method and iterate over a copy:
<code class="python">keys_to_pop = list(d)
for i in keys_to_pop:
    if not d[i]:
        d.popitem(i)</code>

By leveraging these techniques, you can circumvent the "RuntimeError: dictionary changed size during iteration" error when handling dictionaries in Python.

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

Statement:
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