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

遇到的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)#{}
posted @ 2020-06-25 18:48  智、心  阅读(209)  评论(0编辑  收藏  举报