dictionary changed size during iteration

今天遇到这种错误 ‘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}

道行尚浅,欢迎斧正。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值