how to scrutch a dict()

Ethan Furman ethan at stoneleaf.us
Fri Oct 22 09:02:29 EDT 2010


Neil Cerutti wrote:
> On 2010-10-21, James Mills <prologic at shortcircuit.net.au> wrote:
> 
>>Rather than creating a new dict why don't you just do:
>>
>>def _scrunch(d):
>>   for k, v in d.items():
>>      if v is None:
>>         del d[k]
> 
> 
> In Python 3, where items returns an iterator, modifying the
> dictionary in this way may lead to cirrhossis of the dictionary.

Not only cirrhosis, but a RuntimeError:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 2, in _scrunch
RuntimeError: dictionary changed size during iteration

~Ethan~



More information about the Python-list mailing list