Iterating over dict and removing some elements
Bryan
bryanjugglercryptographer at yahoo.com
Wed May 12 03:28:43 EDT 2010
Rebelo wrote:
> 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'}
> >>>
Mostly because there's no reason to get 'v' if you're not going to use
it. That may be just because you simplified the example, and if you
are working in Python 2.x and the real test for whether to delete
involves the value and not just the key, that's a reasonable solution.
On subtler issues, it constucts an unnecessarily long temporary list
in current Python 2.X, and fails in Python 3.x, as Terry Ready
explained.
--
--Bryan
More information about the Python-list
mailing list