Home > OS >  why python avoid size change during iteration in dictionary
why python avoid size change during iteration in dictionary

Time:11-16

I got RuntimeError: Dictionary changed size during iteration in my code.

So I solved it using list(dict.keys()).

But I don't know why python makes error when dictionary is changed during iteration.

why python avoid size change during iteration in dictionary

CodePudding user response:

In Python 3.x and 2.x you can use use list() to force a copy of the keys to be made:

In Python 2.x calling keys made a copy of the keys that you could iterate over while modifying the dict:

But note that in Python 3.x this second method doesn't help with your error because keys returns an a view object instead of copynig the keys into a list.

Quoted from this post.

CodePudding user response:

If you are deleting key in an iteration you will get this. You can transform it to list:

for i in list(dictionary):
   ...

It should work

CodePudding user response:

You can see the answer in Set based dynamic views on PEP 469 -- Migration of dict iteration code to Python 3

In Python 3, the objects returned by d.keys(), d.values() and d. items() provide a live view of the current state of the underlying object, rather than taking a full snapshot of the current state as they did in Python 2. This change is safe in many circumstances, but does mean that, as with the direct iteration API, it is necessary to avoid adding or removing keys during iteration.

  • Related