Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #51138
| References | <51EF2AD8.3080105@stoneleaf.us> <ksnrr9$k4t$1@ger.gmane.org> <CAHVvXxQGCFJe7ud+mwh4zhnq5F7xvHJX1pCtGCjMaFtjBwY=iQ@mail.gmail.com> |
|---|---|
| Date | 2013-07-24 09:58 -0500 |
| Subject | Re: Python 3: dict & dict.keys() |
| From | Skip Montanaro <skip@pobox.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.5040.1374677910.3114.python-list@python.org> (permalink) |
> What do you mean? Why would you want to create a temporary list just to
> iterate over it explicitly or implicitly (set, sorted, max,...)?
Because while iterating over the keys, he might also want to add or
delete keys to/from the dict. You can't do that while iterating over
them in-place.
This example demonstrates the issue and also shows that the
modification actually takes place:
>>> d = dict(zip(range(10), range(10, 0, -1)))
>>> d
{0: 10, 1: 9, 2: 8, 3: 7, 4: 6, 5: 5, 6: 4, 7: 3, 8: 2, 9: 1}
>>> for k in d:
... if k == 3:
... del d[k+1]
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
>>> for k in list(d):
... if k == 3:
... del d[k+1]
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
KeyError: 4
>>> d.keys()
dict_keys([0, 1, 2, 3, 5, 6, 7, 8, 9])
Skip
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Python 3: dict & dict.keys() Skip Montanaro <skip@pobox.com> - 2013-07-24 09:58 -0500
csiph-web