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

Posted venvive

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)#{}

以上是关于dict遍历的时候删除dict中的值报错RuntimeError: dictionary changed size during iteration的主要内容,如果未能解决你的问题,请参考以下文章