Loop thru the dictionary with tuples
Roy Smith
roy at panix.com
Sun May 25 09:22:03 EDT 2014
In article <mailman.10291.1401022510.18130.python-list at python.org>,
Igor Korot <ikorot01 at gmail.com> wrote:
> for (key,value) in my_dict:
> #Do some stuff
>
> but I'm getting an error "Too many values to unpack".
Several people have already given you the right answer, so I'll just
suggest a general debugging technique. Break this down into the
smallest possible steps and print out the intermediate values. When you
write:
> for (key,value) in my_dict:
two things are happening. One is that you're iterating over my_dict,
the other is that you're unpacking the iterated-over things. So break
those up into individual steps:
for thing in my_dict:
(key, value) = thing
and see what that gives you. Do you still get an error? If so, does it
occur on the "for" line or on the assignment line? Hint: in this case,
it will happen on the assignment line, so, your next step is to print
everything out and see what's going on:
for thing in my_dict:
print thing
(key, value) = thing
At this point, it should be obvious what's going on, but just in case
it's not, sometimes I find it useful to be even more verbose:
for thing in my_dict:
print type(thing), repr(thing)
(key, value) = thing
More information about the Python-list
mailing list