"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Avoid the \"RuntimeError: dictionary changed size during iteration\" in Python?

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

Published on 2024-11-10
Browse:547

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:

d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}

for i in d:
    if not d[i]:
        d.pop(i)

To overcome this limitation, various approaches can be employed:

Python 2.x and 3.x:

Force a copy of the keys using 'list':

for i in list(d):

Python 3.x (and later):

Use 'collections.OrderedDict':

from collections import OrderedDict

for i in OrderedDict(d):

Alternative Solutions:

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

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3