Python - RuntimeError: OrderedDict mutated during iteration解决办法

    最近在学习目标追踪,定义好的类在运行的过程中报错,RuntimeError: OrderedDict mutated during iteration,解决办法很多,记录一下我认为最简洁明了的解释和办法。

Python - RuntimeError: OrderedDict mutated during iteration解决办法_第1张图片

   代码实例测试如下:

from collections import OrderedDict

dict = OrderedDict([("a", 1), ("b", 2), ("c", 3)])

for key in dict.keys():  # 在迭代过程中更改OrderedDict,导致报错
    print(key)
    dict["d"] = 5
print(dict)
# RuntimeError: OrderedDict mutated during iteration

for key in list(dict.keys()):
    print(key)
    dict["d"] = 5
print(dict)
# OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 5)])

 

你可能感兴趣的:(基础知识,Python,OrderedDict)