[Tutor] How do I fix this ValueError?

jfouhy@paradise.net.nz jfouhy at paradise.net.nz
Wed Aug 10 03:13:11 CEST 2005


Quoting Nathan Pinno <falcon3166 at hotmail.com>:

> Here is the error:
> 
> Traceback (most recent call last):
>  File "D:\Python24\password.py", line 91, in -toplevel-
>  save_file(sitelist)
>  File "D:\Python24\password.py", line 22, in save_file
>  for site,ID,passcard in sitelist.items():
> ValueError: need more than 2 values to unpack
> 
> Here is the code:
> 
> sitelist = {}

sitelist is a dictionary.  Let's see what the .items() method on dictionaries does:

>>> d = { 1:'foo', 2:'bar', 3:'baz' }
>>> d.items()
[(1, 'foo'), (2, 'bar'), (3, 'baz')]

So, if we iterate over d.items(), we are iterating over a list of tuples, each
two elements long.

>>> for item in d.items():
...  print item
...
(1, 'foo')
(2, 'bar')
(3, 'baz') 

Now, we can "unpack" tuples.  For example:

>>> t = (1, 2)
>>> x, y = t
>>> x
1
>>> y
2

This only works if both sides of the = have the same number of things.

>>> t = (1, 2, 3)
>>> x, y = t            # Not enough variables on the left hand side.
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: too many values to unpack
>>> x, y, z, w = t      # Too many variables on the left hand side.
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: need more than 3 values to unpack

Now can you figure out what the ValueError you were getting means?

-- 
John.


More information about the Tutor mailing list