Somehow unexpectedly encountered such a problem. During the for loop in the dictionary, I need to delete entries from it, but how not to get the error:

 RuntimeError: dictionary changed size during iteration 

I even tried to do a dictionary snapshot before iteration and iterate the twin while removing it from the original.

Example:

 >>> ot={12:'wqe',13:'wqe',14:'wqe',15:'wqe'} >>> ot1=ot >>> for i in ot1: ... del ot[i] ... Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: dictionary changed size during iteration 

How to delete correctly?

upd: figured out

snapshot was appropriate, but made a little bit wrong like this:

 >>> ot={12:'wqe',13:'wqe',14:'wqe',15:'wqe'} >>> ot1=ot.copy() >>> for i in ot1: ... del ot[i] 

    4 answers 4

    You misunderstand the reason for what is happening.
    You ask a question How to delete correctly , but the right question
    How to copy correctly?
    You pass a link to an object from ot to ot1, that is, while ot and ot1 give a pointer to the same dictionary.
    EXAMPLE

     x=['wtf', 'justdoit'] x1=x x1[0]='omg' print x >> ['omg', 'justdoit'] 
    • Actually copying is one of the options that I have tried and it seems the only correct one. I was just surprised that python did not let me delete the value from the dictionary during the cycle, although in fact it deletes and immediately after the first deletion it gives an error. - sonniy
    • As far as I know, this is done on purpose. Something like internal protection against incorrect programming. - ReinRaus
    • Yes indeed. If you delete a key-value pair from an iterable object (a dictionary, for example), then the length value is lost, thereby, forcing at a loss - Spooti

    Perhaps it would be better to write this:

     >>> ot={12:'wqe',13:'wqe',14:'wqe',15:'wqe'} >>> for i in ot**.keys()**: ... del ot[i] 

    To be able to delete items from the dictionary during the iteration, you need to copy the keys:

     d = {12:'wqe',13:'wqe',14:'wqe',15:'wqe'} # ... for key in list(d): if condition(key): del d[key] 

      Your code hints that the element will be deleted by the key, not its value.

       d = {12:'wqe',13:'wqe',14:'wqe',15:'wqe'} for key in list(d): if key == max(d.items(), key=operator.itemgetter(1)): del d[key] 

      And it is impossible for your method for some reason. output: {12: 'wqe', 13: 'wqe', 14: 'wqe', 15: 'wqe'}