gdfgd 发表于 2015-8-25 09:19:12

Python遍历字典删除元素

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

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




会报这个错误:RuntimeError: dictionary changed size during iteration
这种方式Python2可行,Python3还是报上面这个错误。

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




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

1
2
3
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 ***

页: [1]
查看完整版本: Python遍历字典删除元素