码迷,mamicode.com
首页 > 编程语言 > 详细

Python遍历字典删除元素

时间:2015-08-25 12:32:05      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:字典   python3   dict   runtimeerror   

这种方式是一定有问题的:

d = {‘a‘:1, ‘b‘:2, ‘c‘:3}
for key in d:
	d.pop(key)

会报这个错误:RuntimeError: dictionary changed size during iteration


这种方式Python2可行,Python3还是报上面这个错误。

d = {‘a‘:1, ‘b‘:2, ‘c‘:3}
for key in d.keys():
	d.pop(key)

Python3报错的原因是keys()函数返回的是dict_keys而不是list。Python3的可行方式如下:

d = {‘a‘:1, ‘b‘:2, ‘c‘:3}
for key in list(d):
	d.pop(key)


参考:How to avoid “RuntimeError: dictionary changed size during iteration” error?


*** walker ***



Python遍历字典删除元素

标签:字典   python3   dict   runtimeerror   

原文地址:http://walkerqt.blog.51cto.com/1310630/1687624

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!