Iterating over dict and removing some elements
Rebelo
puntabluda at gmail.com
Wed May 12 02:59:44 EDT 2010
On 05/11/2010 05:08 PM, Ulrich Eckhardt wrote:
> Hi!
>
> I wrote a simple loop like this:
>
> d = {}
> ...
> for k in d:
> if some_condition(d[k]):
> d.pop(k)
>
> If I run this, Python complains that the dictionary size changed during
> iteration. I understand that the iterator relies on the internal structure
> not changing, but how would I structure this loop otherwise?
>
> My first approach was to simply postpone removing the elements, but I was
> wondering if there was a more elegant solution.
>
> Thanks!
>
> Uli
>
i am wondering why not like this:
>>> d = {1: 'one', 2: 'two', 3: 'three'}
>>> for k,v in d.items():
... if k==1:
... del d[k]
...
>>> d
{2: 'two', 3: 'three'}
>>>
More information about the Python-list
mailing list