pythonpython-3.xiterationordereddictionarymutated

RuntimeError: OrderedDict mutated during iteration (Python3)


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

Solution

  • 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()