Dictionary infinite loop is exiting unexpectedly Dictionary infinite loop is exiting unexpectedly python python

Dictionary infinite loop is exiting unexpectedly


There is no guarantee that you will iterate over all your dict entries if you mutate it in your loop. From the docs:

Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

You could create an "enumerated" infinite loop similar to your initial attempt using itertools.count(). For example:

from itertools import countfor i in count():    print(i)    # don't run this without some mechanism to break the loop, i.e.    # if i == 10:    #     break# OUTPUT# 0# 1# 2# ...and so on


In this case, like @benvc wrote, this is not guaranteed to work. But in case you wonder why does it work in C-Python:

The C-Python implementation destroys the dict object after some inserts and copies it to a new space in memory. It does not care about deletions. So when this happens, the loop notices it and breaking with an exception.

Check out this link if you want to read more about this, and many other interesting python internals here.

https://github.com/satwikkansal/wtfpython#-modifying-a-dictionary-while-iterating-over-it


I just tested your code in python2 and python3

python3 output0,1,2,3,4python20,1,2,3,4,5,6,7

One thing comes to mind that could be going on. Either there is only a certain amount of memory being allocated in your dictionary when you create the first key value and when you delete the key value we do not allocate any memory or deallocate the memory you are just removing the value. Once all the allocated memory is used it exits. Because if you run without that del you will get this error

RuntimeError: dictionary changed size during iteration

So python creates enough memory for that key value and a few more and once it is used up theres no more memory allocated for your dictionary.