Python 3: dict & dict.keys()

Skip Montanaro skip at pobox.com
Wed Jul 24 10:58:21 EDT 2013


> 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



More information about the Python-list mailing list