dictionary size changed during iteration

Roy Smith roy at panix.com
Fri Apr 22 09:15:46 EDT 2011


In article <mailman.644.1303306435.9059.python-list at python.org>,
 Peter Otten <__peter__ at web.de> wrote:

> You now have to create the list explicitly to avoid the error:
> 
> >>> d = dict(a=1)
> >>> keys = list(d.keys())
> >>> for k in keys:
> ...     d["b"] = 42
> ...

That works, but if d is large, it won't be very efficient because it has 
to generate a large list.

If d is large, and the number of keys to be mutated is relatively small, 
a better solution may be to do it in two passes.  The first loop 
traverses the iterator and builds a list of things to be changed.  The 
second loop changes them.

changes = [ ]
for key in d.iterkeys():
  if is_bad(key):
    changes.append(key)
for key in changes:
  d[key] = "I'm not dead yet"

Both solutions are O(n), but the second may run significantly faster and 
use less memory.



More information about the Python-list mailing list