[Tutor] use of the newer dict types
eryksun
eryksun at gmail.com
Fri Jul 26 00:54:44 CEST 2013
On Thu, Jul 25, 2013 at 6:37 PM, Dave Angel <davea at davea.name> wrote:
>
> For dictionaries, instead of returning a list, keys() returns a dictionary
> view. See http://docs.python.org/3/library/stdtypes.html#dict-views
>
> What's not clear to me is whether this dictionary view object is safe to use
> when the dictionary is changing. The page referenced above seems to say
> both yes and no.
The view isn't an iterator. A separate iterator gets created for that:
>>> d = {'a': 1}
>>> keys = d.keys()
>>> it = iter(keys)
>>> d['b'] = 2 # invalidate "it"
>>> list(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
This creates and iterates a new dict_keyiterator:
>>> list(keys)
['b', 'a']
More information about the Tutor
mailing list