Iterating over dict and removing some elements

Ulrich Eckhardt eckhardt at satorlaser.com
Tue May 11 11:08:02 EDT 2010


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

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932




More information about the Python-list mailing list