modify dictionary while iterating

Peter Otten __peter__ at web.de
Fri Nov 11 03:13:50 EST 2005


s99999999s2003 at yahoo.com wrote:

> hi
> I wish to pop/del some items out of dictionary while iterating over it.
> a = { 'a':1, 'b':2 }
> for k, v in a.iteritems():
>     if v==2:
>         del a[k]
> 
> the output say RuntimeError: dictionary changed size during iteration
> how can i suppress this message in an actual script and still get the
> final value of the dict?
> is it something like try/except/else statment?
> try:
>    for v,k in a.iteritems():
>      if v==something:
>          del a[k]
> except RuntimeError:
>    < don't know what to do here>
> else:
>    < should i include this part ? >
> 
> what other ways can i do this ? thanks for any help.

If you expect to delete only a few items:

>>> a = dict(a=1, b=2, c=3, d=2)
>>> delenda = [k for k, v in a.iteritems() if v == 2]
>>> for k in delenda:
...     del a[k]
...
>>> a
{'a': 1, 'c': 3}

If you expect to delete most items:

>>> a = dict(a=1, b=2, c=3, d=2)
>>> a = dict((k, v) for k, v in a.iteritems() if v != 2)
>>> a
{'a': 1, 'c': 3}

or (if rebinding a is not an option)

>>> a = dict(a=1, b=2, c=3, d=2)
>>> for k, v in a.items():
...     if v == 2:
...             del a[k]
...
>>> a
{'a': 1, 'c': 3}

Peter




More information about the Python-list mailing list