1

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 ?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
jmamath
  • 190
  • 2
  • 13

2 Answers2

2

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]
elaaf
  • 81
  • 3
0

You should use list() for od.keys() to create the copy object of od.keys() as shown below:

from collections import OrderedDict
 
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4 
         # ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
for key in list(od.keys()):
    od[key+"_"] = od.pop(key)
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129