Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to delete a dictionary key while iterating over it in python3: "RuntimeError: dictionary changed size during iteration"

I am trying to delete a key from a dictionary while iterating through it. When removing the key from the dictionary I get:
RuntimeError: dictionary changed size during iteration

My code:

mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}

for k, v in mydict.items():
    if k == 'two':
        del(mydict[k])
        continue
    print(k)

To avoid this I copied the same dictionary to another dictionary and then I tried to remove the content from the copied dictionary while iterating the previous dictionary. But still, I am getting the error.

mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}

new_dict = mydict
for k, v in mydict.items():
    if k == 'two':
        del(new_dict[k])
        continue
    print(k)

So can anyone please help to solve this issue.

like image 781
Arijit Panda Avatar asked Jul 26 '26 21:07

Arijit Panda


1 Answers

For Python-3-x the easy way is to convert the dict into a list() in the iteration:

mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}

for k, v in list(mydict.items()):
    if k == 'two':
        del(mydict[k])
        continue   
    print(k)
like image 171
Ribes Avatar answered Jul 28 '26 09:07

Ribes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!