2

I am trying to delete a key from a dictionary while iterating through it. While directly trying to remove the key form the dictionary I was getting RuntimeError: dictionary changed size during iteration. My code for that is.

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.

Arijit Panda
  • 1,581
  • 2
  • 17
  • 36
  • Why would you iterate a dictionary simply to delete a specific key? – jpp Mar 23 '18 at 10:01
  • Possible duplicate of [How to delete items from a dictionary while iterating over it?](https://stackoverflow.com/questions/5384914/how-to-delete-items-from-a-dictionary-while-iterating-over-it) – Ribes Mar 23 '18 at 10:25
  • @Ribes & @jpp - My query is related the deletion of `new_dict` key. I was iterating `mydict` dictionary but unable to delete `new_dict` key. – Arijit Panda Mar 23 '18 at 10:29

5 Answers5

2

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)
Ribes
  • 455
  • 2
  • 17
1

You cannot delete a key-value pair while iterating the dictionary. Instead you can use a dict comprehension

Ex:

mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
print({k:v for k,v in mydict.items() if k != 'two'})

Output:

{'four': 4, 'three': 3, 'one': 1}
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • I was trying to delete the keys form the copied dictionary as I was not iterating that dictionary. Is python not allow to remove any dictionary key while iterating through a dictionary? – Arijit Panda Mar 23 '18 at 07:55
  • `new_dict = mydict` does not work the way you think it does. Python has a different mechanism. You need to read about copying objects in python. – Rakesh Mar 23 '18 at 07:58
0

If you know the key in advance and wish to delete it from your dictionary:

  • Do not try to delete it while iterating the dictionary.
  • Do not copy the dictionary, iterate and delete.
  • Do not create a list of tuples from the dictionary, iterate and delete.

Instead, just use del mydict['two'].

Usually, there is no reason why you need to delete a known key while iterating, especially since dictionaries are considered unordered and you cannot tell when you will reach the selected key.

jpp
  • 159,742
  • 34
  • 281
  • 339
0

a simpler way is to make a shallow copy of the dict before iterating, like this:

t = "t"
mydict = dict()
mydict["1"] = "t";
mydict["2"] = "a"
print(mydict)
for key, value in mydict.copy().items():
    if value == t:
        del mydict[key]

print(trades)
-1

You're still getting error in second code, cause new_dict is just another variable referencing the same object. You can simply copy my_dict instead of making another variable pointing to it.

new_dict=my_dict.copy()

Sadly dict do not have deep copy method, so it have to be imported:

from copy import deepcopy
new_dict=deepcopy(my_dict)

For more info look here.

Piotr Banaś
  • 198
  • 1
  • 8
  • In the case yes, but my_dict.copy() is shallow copy. If You want deep copy just "from copy import deepcopy" and then use deepcopy. – Piotr Banaś Mar 23 '18 at 09:02