今天遇到这种错误 ‘RuntimeError: dictionary changed size during iteration’
字典在迭代时无法改变大小, 英语渣 轻喷。
>>> test = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> for i in test.keys():
test.pop(i)
1
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
for i in test.keys():
RuntimeError: dictionary changed size during iteration
研究了下发现通过复制可以进行删除操作
>>> temp = test.copy()
>>> temp
{'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> for k in test.keys():
temp.pop(k)
2
3
4
5
>>> temp
{}
或者list化键然后进行删除操作>>> test = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> for k in list(test.keys()):
test.pop(k)
1
2
3
4
5
>>> test
{}
>>>
有个很有趣的现象,直接进行删除操作的时候在报错的同时也删除了迭代的第一个键>>> test = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> for i in test.keys():
test.pop(i)
1
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
for i in test.keys():
RuntimeError: dictionary changed size during iteration
>>> test
{'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> for i in test.keys():
test.pop(i)
2
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
for i in test.keys():
RuntimeError: dictionary changed size during iteration
>>> test
{'c': 3, 'd': 4, 'e': 5}
>>> for i in test.keys():
test.pop(i)
3
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
for i in test.keys():
RuntimeError: dictionary changed size during iteration
>>> test
{'d': 4, 'e': 5}
道行尚浅,欢迎斧正。