Iterating over dict and removing some elements
Terry Reedy
tjreedy at udel.edu
Tue May 11 15:45:05 EDT 2010
On 5/11/2010 11:29 AM, Jerry Hill wrote:
> On Tue, May 11, 2010 at 11:08 AM, Ulrich Eckhardt
> <eckhardt at satorlaser.com> wrote:
>> My first approach was to simply postpone removing the elements, but I was
>> wondering if there was a more elegant solution.
>
> Iterate over something other than the actual dictionary, like this:
>
> d = {1: 'one', 2: 'two', 3: 'three'}
>
> for k in d.keys():
> if d[k] == 'two':
> d.pop(k)
This, as written, does not work in 3.1, where d.keys is a view of the
dict. Nor does
for k in filter(lambda k: d[k] == 'two', d):
d.pop(k)
But these do
for k in list(filter(lambda k: d[k] == 'two', d)):
d.pop(k)
for k in [k for k in d if d[k] == 'two']:
d.pop(k)
Rather than make an external list of *all* keys, one only needs to make
a list of keys to be removed, which often will be much smaller.
Terry Jan Reedy
More information about the Python-list
mailing list