首页 > 其他 > 详细

dict遍历的时候删除dict中的值报错RuntimeError: dictionary changed size during iteration

时间:2020-06-25 19:57:36      阅读:72      评论:0      收藏:0      [点我收藏+]

遇到的error,当遍历字典的时候修改字典数据会报错,例如

temp = {‘name‘: ‘Mike‘, ‘age‘: ‘25‘, ‘shengao‘: 180, ‘weight‘: 80}
for key,value in temp.items():
    del temp[key]
#RuntimeError: dictionary changed size during iteration

解决使用浅拷贝或者深拷贝

import copy
temp = {‘name‘: ‘Mike‘, ‘age‘: ‘25‘, ‘shengao‘: 180, ‘weight‘: 80}
copy_temp = copy.copy(temp)
for key,value in copy_temp.items():
    del temp[key]
print(temp)#{}

dict遍历的时候删除dict中的值报错RuntimeError: dictionary changed size during iteration

原文:https://www.cnblogs.com/venvive/p/13192579.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!