modify dictionary while iterating

Ben Finney bignose+hates-spam at benfinney.id.au
Fri Nov 11 09:19:39 CET 2005


s99999999s2003 at yahoo.com wrote:
> I wish to pop/del some items out of dictionary while iterating over
> it.

Iterate over a copy.

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

-- 
 \      "I know the guy who writes all those bumper stickers. He hates |
  `\                                      New York."  -- Steven Wright |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list