RuntimeError: OrderedDict mutated during iteration (Python3)

30.9k views Asked by At

Getting the error mentioned in the title. The below mentioned functioned is called by another function that is called through a POST api.

Error is on the line below the print statement. Don't know what the error means and why its coming. The same code used to run a week back.

def remove_individual_stops(ordered_parkstop_dict, relevant_data):
    new_ordered_parkstop_dict = ordered_parkstop_dict
    for key, value in ordered_parkstop_dict.items():
        if len(value) == 0:
            for k,v in ordered_parkstop_dict.items():
                if key in v:
                    new_ordered_parkstop_dict.pop(key)
        print (type(ordered_parkstop_dict), ordered_parkstop_dict)
        for k,v in ordered_parkstop_dict.items():
            klist = []
            keylist = []
            if value and v:
                if len(v)==1 and len(value)==1:
                    klist.append(k), keylist.append(key)
                if (keylist == v) and (klist == value and len(value) == 1):
                    new_ordered_parkstop_dict.pop(key)
    return new_ordered_parkstop_dict
2

There are 2 answers

7
blhsing On BEST ANSWER

You assigned new_ordered_parkstop_dict with a reference of the ordered_parkstop_dict dict, so when you iterate over ordered_parkstop_dict.items() and mutate new_ordered_parkstop_dict by popping it, you mutate ordered_parkstop_dict too, which can't be done since your loop is iterating over ordered_parkstop_dict.

You should assign a copy of ordered_parkstop_dict to new_ordered_parkstop_dict instead. Change:

new_ordered_parkstop_dict = ordered_parkstop_dict

to:

new_ordered_parkstop_dict = ordered_parkstop_dict.copy()
0
Super Kai - Kazuya Ito On

You should assign the copy object of ordered_parkstop_dict to new_ordered_parkstop_dict with dict() or copy() as shown below:

new_ordered_parkstop_dict = dict(ordered_parkstop_dict)
new_ordered_parkstop_dict = ordered_parkstop_dict.copy()

In addition, you can check if the objects are the same with is operator as shown below:

person1 = {"name": "John", "age": 36}
person2 = person1
print(person1 is person2) # True
person1 = {"name": "John", "age": 36}
person2 = dict(person1)
print(person1 is person2) # False
person1 = {"name": "John", "age": 36}
person2 = person1.copy()
print(person1 is person2) # False