[Tutor] use of the newer dict types

eryksun eryksun at gmail.com
Fri Jul 26 03:27:58 CEST 2013


On Thu, Jul 25, 2013 at 7:51 PM, Dave Angel <davea at davea.name> wrote:
>
> And it's apparently safe to change the dictionary after creating the view,
> UNTIL the iterator is created.

Notice the error the iterator raised in my example was just about the
dict changing size. If the dict changes between steps while remaining
the same size, the iterator doesn't have a clue:

    >>> d = dict.fromkeys('abcdef')
    >>> d2 = dict.fromkeys('ghijkl')

    >>> keys = d.keys()
    >>> it = iter(keys)
    >>> next(it)
    'f'
    >>> next(it)
    'e'

    >>> d.clear()
    >>> d.update(d2)
    >>> list(it)
    ['l', 'k', 'j', 'i', 'h']

'g' got skipped. The result here depends on the iterator's current
index into the hash table and the positions that the updated values
hash to.

> 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?

It already has the hash table. It just has to iterate it looking for
non-NULL values, and keep track of the previous index between calls to
__next__().

Another bit of state the iterator maintains is a length hint, which
helps to optimize memory allocation when using the iterator to create
a new sequence:

    >>> d = dict.fromkeys('abcdef')
    >>> it = iter(d)
    >>> it.__length_hint__()
    6
    >>> next(it)
    'f'
    >>> it.__length_hint__()
    5


More information about the Tutor mailing list