[Python-3000] Spooky behavior of dict.items() and friends

Michael Urman murman at gmail.com
Wed Apr 2 15:51:40 CEST 2008


On Wed, Apr 2, 2008 at 1:39 AM, "Martin v. Löwis" <martin at v.loewis.de> wrote:
> > I'd say not clear, for two reasons. One is that I pretty much never
> > use keys() in a for loop, I just use the dictionary.
>
> Ok. Consider items() then. Again, I claim that the common use of
> items() is to iterate over it.
>
> ,keys() should clearly behave the same as .items().

The biggest concern I have is over whether the following works:

    for i, k in enumerate(d.keys()):
        if i % 2: del d[k]

If this code works as is in py3k, I have no concerns over whether
keys(), etc., return snapshots or live views. If this code instead
requires the snapshot that list(d) or list(d.keys()) provides, then
I'm lightly worried that this will be a repeated source of error for
folks who have recently migrated from 2.x to 3.x and haven't really
internalized that keys() no longer returns a copy.

It's only a light worry as there are plenty people who make that
mistake in 2.x by leaving off the keys() entirely. And I hardly think
this light worry is worth changing the behavior that was decided on
months ago.

-- 
Michael Urman


More information about the Python-3000 mailing list