RuntimeError: OrderedDict mutated during iteration

created at 10-28-2021 views: 4

problem

OrderedDict is used to filter the search results in the project. There is a rule to delete some of the elements. The above error is reported when the following code is used, the programming language py3.7

from collections import OrderDict
search_res = OrderedDict([("k1", "v1"), ("k2", "v2"), ("k3", "v3")])
for k, v in search_res.items():
    if k == 'k2':   # Suppose the rule is to delete k2
        del search_res[k]

The above program will report this problem:

RuntimeError: OrderedDict mutated during iteration

reason

Operation while traversing causes the element to change, so that the traversed object is not a fixed container, resulting in runtimeError

for k, v in search_res.items()
    ...
    del search_res[k]

Solution

When traversing, fix the traversal list

for k in list(search_res.keys()):  # Fixed the objects to be iterated
    if k == 'v2':
        del search_res[k]
created at:10-28-2021
edited at: 10-28-2021: