modify dictionary while iterating

skip at pobox.com skip at pobox.com
Fri Nov 11 09:18:17 EST 2005


    >> I wish to pop/del some items out of dictionary while iterating over
    >> it.

    Ben> Iterate over a copy.

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

Or iterate over just a copy of the keys:

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

Skip



More information about the Python-list mailing list