首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python遍历字典删除元素错误

python遍历字典删除元素错误

作者头像
生信编程日常
发布于 2020-04-01 16:03:38
发布于 2020-04-01 16:03:38
3.8K0
举报

今天写了这么一段代码,类似于这样:

代码语言:javascript
复制
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转化为列表迭代:

代码语言:javascript
复制
keys = list(d.keys())
for key in keys:
    if key == 'three':
        del(d[key])

字典d返回: {'one': 1, 'two': 2, 'four': 4, 'five': 5}

欢迎关注公众号!

生信编程日常

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档