pop method question

Paul Rubin http
Sun Mar 4 00:36:14 CET 2007

James Stroud <jstroud at mbi.ucla.edu> writes:
> for akey in dict1:
>    if some_condition(akey):
>      dict2[akey] = dict2.pop(akey)
> Which necessitates a key is a little cleaner than your latter example.

Yeah, I also think removing keys from a dict while iterating over it
(like in Steven's examples) looks a bit dangerous dangerous.

Assuming you meant "dict1.pop" instead ot dict2.pop above, your
example might be written

    dict2 = dict((k, dict1.pop(k)) for k in dict1 if some_condition(k))

avoiding some namespace pollution etc.

More information about the Python-list mailing list