当前位置:首页 > Python教程 > python技巧

python错误之RuntimeError: dictionary changed size during iteration

pythonn报错信息:
C:UsersAdministratorAppDataLocalProgramsPythonPython36-32python.exe C:/Users/Administrator/PycharmProjects/pythondemo/maptest.py
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/pythondemo/maptest.py", line 5, in <module>
for line in maps.keys():
RuntimeError: dictionary changed size during iteration

# python2中实现遍历的同时删除字典中的元素;python3中运行报错信息:
"""
C:UsersAdministratorAppDataLocalProgramsPythonPython36-32python.exe C:/Users/Administrator/PycharmProjects/pythondemo/maptest.py
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/pythondemo/maptest.py", line 5, in <module>
for line in maps.keys():
RuntimeError: dictionary changed size during iteration
"""
# maps = {1:"李明",2:"丹尼"}
# for line in maps.keys():
# if(line == 2):
# maps.pop(line)
# print(maps)

# python3中实现遍历的同时删除字典中的元素
maps = {1:"李明",2:"丹尼"}
for line in list(maps.keys()):
if(line == 2):
maps.pop(line)
print(maps)

原文:http://www.cnblogs.com/g177w/p/err1.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!