Iterating over dict and removing some elements

Adi Eyal adi at digitaltrowel.com
Wed May 12 08:13:05 EDT 2010


> ---------- Forwarded message ----------
> From: Bryan <bryanjugglercryptographer at yahoo.com>
> To: python-list at python.org
> Date: Tue, 11 May 2010 23:59:29 -0700 (PDT)
> Subject: Re: Iterating over dict and removing some elements
> Terry Reedy wrote:
> [...]
>> for k in [k for k in d if d[k] == 'two']:
>>          d.pop(k)
>
> We have a winner.
>

also

foo = lambda k, d : d[k] == "two"
d = dict([(k, d[k]) for k in d.keys() if not foo(k, d)])

incidentally, this is marginally slower than pops and dels but has the
benefit of not modifying the original dict if that's what you need.

Adi



More information about the Python-list mailing list