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)#{}
上一篇:C# json字符串转化成Dictionary


下一篇:基于哈夫曼(haffuman)算法的文件压缩的实现(C语言)(转)