0

I have a legacy code where value of a specific key is popped and assigned to new key while iterating the dictionary. This logic was working in python 3.7 but in 3.8 it will throw RuntimeError: dictionary keys changed during iteration. How can this be achieved in python 3.8

sample code:

d={'one':1 , 'two':2 ,'three':3}
for k,v in d.items():
    if k == 'two':
        d['new']=d.pop(k)
print(d)

o/p in 3.7:

(dev) karb@N-5CG6473V5M:~$ python test_dict.py 
{'one': 1, 'three': 3, 'new': 2}

o/p in 3.8:

(dev) karb@N-5CG6473V5M:~$ python test_dict.py 
Traceback (most recent call last):
  File "test_dict.py", line 5, in <module>
    for k,v in d.items():
RuntimeError: dictionary keys changed during iteration
kart1657
  • 78
  • 8
  • 5
    Use `for k,v in list(d.items()):` to make a copy first. – Aaron Apr 09 '21 at 10:41
  • 2
    Does this answer your question? [Modifying a Python dict while iterating over it](https://stackoverflow.com/questions/6777485/modifying-a-python-dict-while-iterating-over-it) – Aaron Apr 09 '21 at 10:45
  • "where value of a specific key is popped and assigned to new key while iterating the dictionary." Do you understand why this causes difficulties with the logic? For example, should the new key be included later on in the iteration, or not? If so, at what point? – Karl Knechtel Apr 09 '21 at 10:51

0 Answers0