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

Christian Heimes lists at cheimes.de
Wed Apr 2 16:53:00 CEST 2008


Michael Urman schrieb:
>     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.

The 2to3 fixer does the right thing. enumerate(d.keys()) does not have
the same effect in Python 3.0 as it has in Python 2.x.

--- test.py (original)
+++ test.py (refactored)
@@ -1,3 +1,3 @@
-for i, k in enumerate(d.keys()):
+for i, k in enumerate(list(d.keys())):
     if i % 2: del d[k]


Christian



More information about the Python-3000 mailing list