[Tutor] Data persistence problem

Steven D'Aprano steve at pearwood.info
Sat Jun 22 13:22:03 CEST 2013


On 22/06/13 12:26, Jim Mooney wrote:
> On 21 June 2013 16:56, ALAN GAULD <alan.gauld at btinternet.com> wrote:
>
>
>> if isinstance(dict(),typein):
>>     try: newdict = dict(zip(dl[::2],dl[1::2]))
>>     except TypeError:
>>      raise ValueError("input lists must be an even length")
>
> Not sure why TypeError and ValueError is used. I would have thought
> StopIteration but explain your logic on that as I'm unclear. But the
> Exception never tripped, either way. I tried different length
> iterables in the zip, but it looks like dict knows tostop before it
> trip thems. Only next() does raises the exception. Unless I am
> confused ;')

It's not dict which is smart in this case, but zip(), which stops when one of the sequences has run out:

py> zip("abcdefg", "1234", "ABCDEFGHIJKLMN")
[('a', '1', 'A'), ('b', '2', 'B'), ('c', '3', 'C'), ('d', '4', 'D')]


In Python 3, zip is "lazy" and only returns items on request, rather than "eager" returning them all at once in a list. To get the same result in Python 3, use list(zip(...)) instead.


If you arrange for dict to see a missing value, it will raise ValueError:


py> dict([('a', 1), ('b', 2), ('c',)])
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #2 has length 1; 2 is required



>>>> zippy = zip([1,2],[3,4,5,6,7,8,9])
>>>> D = dict(zippy)
>>>> D
> {1: 3, 2: 4} # dict works fine
>>>> next(zippy) # exhausting zippy raises StopIteration
> Traceback (most recent call last):
>    File "<string>", line 301, in runcode
>    File "<interactive input>", line 1, in <module>
> StopIteration

That's because zippy is already exhausted by dict, and once exhausted, it stays exhausted.



-- 
Steven


More information about the Tutor mailing list