pythonpython-3.xiterationordereddictmutated

Changing key name in OrderedDict in a loop cause RuntimeError: OrderedDict mutated during iteration


Consider the following problem, I have an OrderedDict, and only want to change the name of the keys. We can do it line by line with the following command:

od[new_key] = od.pop(old_key)

However, if I try to do it in a loop I get a RuntimeError: OrderedDict mutated during iteration

Here is a short example to reproduce the problem:

from collections import OrderedDict
 
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4 

for key in od.keys():
    od[key+"_"] = od.pop(key)  

How would you solve the problem ?


Solution

  • You are attempting to modify the same dictionary over which (Dict keys) you are iterating over, which is not allowed. Similar to how you can not modify the contents of the Python list that you are iterating over.

    Create a list for the dictionary keys, iterate over the list and update the dictionary keys.

        my_dic_keys = list(od.keys())
    
        for key in my_dic_keys:
            od[key+"_"] = od[key]
            del od[key]