RuntimeError:字典在迭代期间改变了大小

RuntimeError:字典在迭代期间改变了大小

RuntimeError: dictionary changed size during iteration

Python“RuntimeError: dictionary changed size during iteration”发生在我们在迭代字典时改变字典的大小时。要解决该错误,请使用该copy()方法创建可以迭代的字典的浅表副本,例如my_dict.copy().

runtimeerror 字典在迭代期间改变了大小

下面是错误如何发生的示例。

主程序
my_dict = {'a': 1, 'b': 2, 'c': 3} # ⛔️ RuntimeError: dictionary changed size during iteration for key in my_dict: print(key) if key == 'b': del my_dict[key]

迭代字典时不允许更改字典的大小。

解决该错误的一种方法是使用该dict.copy方法创建字典的浅表副本并迭代该副本。

主程序
my_dict = {'a': 1, 'b': 2, 'c': 3} for key in my_dict.copy(): print(key) if key == 'b': del my_dict[key] print(my_dict) # 👉️ {'a': 1, 'c': 3}
Iterating over a dictionary and changing its size messes up with the iterator, so creating a shallow copy and iterating over the copy solves the issue.

You can also convert the keys of the dictionary to a list and iterate over the
list of keys.

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} for key in list(my_dict.keys()): print(key) if key == 'b': del my_dict[key] print(my_dict) # 👉️ {'a': 1, 'c': 3}

The dict.keys
method returns a new view of the dictionary’s keys.

main.py
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.keys()) # 👉️ dict_keys(['id', 'name'])

We used the list() class to create a copy of the keys in the example.

You can also use the dict.items() method in a similar way.

However, notice that when using dict.items(), we have access to the key and
value of the current iteration.

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} for key, value in list(my_dict.items()): print(key, value) # 👉️ a 1, b 2, c 3 if key == 'b': del my_dict[key] print(my_dict) # 👉️ {'a': 1, 'c': 3}

We used the list() class to create a copy of the dictionary’s items.

The dict.items
method returns a new view of the dictionary’s items ((key, value) pairs).

main.py
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.items()) # 👉️ dict_items([('id', 1), ('name', 'Alice')])

Which approach you pick is a matter of personal preference. I’d go with using
the dict.copy()
method.

The method returns a shallow copy of the dictionary, so it’s quite easy to read
and solves the issue of not being able to iterate over a dictionary and change
its size.

Conclusion #

The Python “RuntimeError: dictionary changed size during iteration” occurs
when we change the size of a dictionary when iterating over it. To solve the
error, use the copy() method to create a shallow copy of the dictionary that
you can iterate over, e.g. my_dict.copy().