modify dictionary while iterating

s99999999s2003 at yahoo.com s99999999s2003 at yahoo.com
Fri Nov 11 02:45:54 EST 2005


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.




More information about the Python-list mailing list