[Python-3000] Spooky behavior of dict.items() and friends
Antoine Pitrou
solipsis at pitrou.net
Wed Apr 2 16:43:33 CEST 2008
Michael Urman <murman <at> gmail.com> writes:
> The biggest concern I have is over whether the following works:
>
> for i, k in enumerate(d.keys()):
> if i % 2: del d[k]
>
Well:
Python 3.0a3+ (py3k, Mar 30 2008, 21:14:40)
[GCC 4.2.3 (4.2.3-5mnb1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> for i, k in enumerate(d.keys()):
... if i % 2: del d[k]
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
The "problem" here is that while d.keys() returns the view, enumerate() in turn
calls iter() on the view and that iterator fails on you when dictionary changed
size (as iterkeys() already did in 2.x).
Regards
Antoine.
More information about the Python-3000
mailing list