Iterating over dict and removing some elements

Paul Rubin no.email at nospam.invalid
Fri May 14 16:19:59 EDT 2010


Bryan <bryanjugglercryptographer at yahoo.com> writes:
> In Python 3.X, and in Python 2.X starting with 2.4, you can drop the
> square brackets and avoid creating an extra temporary list:
>
> d = dict((k, d[k]) for k in d.keys() if not foo(k, d))

In 2.x, I think you want d.iterkeys() rather than d.keys() to avoid
making a list with all the keys.  Or you can just say

  d = dict((k, d[k]) for k in d if not foo(k, d))



More information about the Python-list mailing list