今天写了这么一段代码,类似于这样:
d = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5}
for key in d:
if key == 'three':
del d[key]
这里报了一个这样的错误:
RuntimeError: dictionary changed size during iteration;
去查了一下,发现官方的一个解释:
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. During such an iteration, the dictionary should not be modified, except that setting the value for an existing key is allowed (deletions or additions are not, nor is the update() method). This means that we can write
for k in dict: ...
which is equivalent to, but much faster than
for k in dict.keys(): ...
as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.
也就是说在迭代字典的时候,每次迭代不得循环删除或者更新字典。并且提到for k in dict与for k in dict.keys()功能一样,并且更快。
这个错误的解决方式是将keys转化为列表迭代:
keys = list(d.keys())
for key in keys:
if key == 'three':
del(d[key])
字典d返回:
{'one': 1, 'two': 2, 'four': 4, 'five': 5}
欢迎关注公众号!
生信编程日常
网友评论