dictionary size changed during iteration

Mark Niemczyk prahamark at gmail.com
Fri Apr 22 08:39:23 EDT 2011

As of Python 3.x (which I suspect you are running):

"The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.", and 

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

     see: http://docs.python.org/release/3.1.3/library/stdtypes.html#dict-views

On my system:
ActivePython (ActiveState Software Inc.) based on
Python 3.2 (r32:88445, Feb 21 2011, 11:25:33) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> ukeys = {}
>>> type(ukeys.keys())
<class 'dict_keys'>

So, to achieve your objective, one solution could be to change the ukeys assignment statement to:

     ukeys = list(self.updates.keys())

Hope this helps,

Mark N.

More information about the Python-list mailing list