码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-06-25 19:20:31      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:浅拷贝   import   imp   报错   删除   temp   int   遍历字典   lan   

遇到的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

标签:浅拷贝   import   imp   报错   删除   temp   int   遍历字典   lan   

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

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