python遍历字典删除元素错误

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

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}

欢迎关注!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 个人笔记,方便自己查阅使用 Py.LangSpec.Contents Refs Built-in Closure ...
    freenik阅读 67,805评论 0 5
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,546评论 0 13
  • 函数调用 Built-in Functions abs(x) Return the absolute value ...
    叫我七夜阅读 1,219评论 0 0
  • 【Day6课后实践】这是2018年8月10日“崔律·100天精力和时间管理训练营”第1.5讲的课后实践。<实践事项...
    孔雀勇士阅读 190评论 0 0
  • 最近听了刘媛媛的《寒门难出贵子》,振奋于“命运手里也是有漏网之鱼的”。“三个月考上北大一点都不难”令我对她的方法有...
    今夜有戏阅读 199评论 0 0