modify dictionary while iterating

François Pinard pinard at iro.umontreal.ca
Fri Nov 11 09:41:40 EST 2005


[s99999999s2003 at yahoo.com]

>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]

A simple change would be using "items()" instead of "iteritems()".

Or else, you may prefer to loop over keys, and retrieve values, either:

    for k in a.keys():
        if a[k] == 2:
            del a[k]

or:

    for k in set(a):
        if a[k] == 2:
            del a[k]

But in no way, you may directly iterate over the original dictionary 
while altering its keys, this is explicitly forbidden in Python.

-- 
François Pinard   http://pinard.progiciels-bpi.ca



More information about the Python-list mailing list