[Tutor] use of the newer dict types

Dave Angel davea at davea.name
Fri Jul 26 01:51:28 CEST 2013


On 07/25/2013 06:54 PM, eryksun wrote:
> 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']

OK, so the view is apparently an iterable.

And it's apparently safe to change the dictionary after creating the 
view, UNTIL the iterator is created.  And perhaps the dictionary isn't 
actually traversed till the iterator is created.

I still don't see the advantage.  Isn't the iterator going to be as big 
as the list would have been, and take just as long to build?

-- 
DaveA



More information about the Tutor mailing list