AAA AAA - 6 days ago 7
Python Question

Too many values to unpack...but there aren't

So url is a dictionary, I am iterating over its keys. Then for each key, I am trying to unpack the values in that dictionary.

for key in url:
print len(url[key])
for val, date in url[key]:
print val, date


The dictionary is in a format like this:

url[key] = (['value','value2','value3'],'date')

Where a key corresponds to a tuple of length 2. However, I keep getting the following error:

2

Traceback (most recent call last):
File "insertCIF.py", line 10, in <module>
for val, date in url[key]:
ValueError: too many values to unpack


Which is funny because that 2 at the top is the result of the print length statement. So how am I trying to unpack too many values, when I am trying to unpack 2 values, and I verified that the length of the tuple is indeed 2?

I know I can do url.items or iteritems as a workaround (and it does work) but this issue has me curious and I can't figure it out or troubleshoot it.

Answer

Because you are trying to iterate over the value of url[key] using for loop. In order to assign the values, instead you should be doing just:

val, date = url[key]: