Still Switching to Python: Iterating through dictionary lists

Last night while developing a module, I ran into a situation I never thought I would encounter, a syntax problem. Why the surprise? Python is fairly sparse when it comes to syntax. The lack of keywords, brackets, and semicolons makes code look more like a hodgepodge of pseudo code than a programming language.

While trying to implement a simple iteration through a dictionary list, I ran into a syntax error with the following code:

for k,v in dictList.items():
print "%s=%s \n" % k,v

This resulted in the following error: ‘ValueError: need more than 1 value to unpack’.

After a bit of searching and experimenting, I figured out that I was missing the parenthesis around the ‘extraction values’. This was confusing because most of the examples I found did not cover the more familiar¬† iteration patterns in C like languages. To correct the error above, you would type:

for (k,v) in dictList.items():
print "%s=%s \n" % (k,v)

During my search for the solution. Most of the examples I found for iterating through lists looked more like the following:

print "\n".join(["%s=%s" % (k,v) for k,v in dictList.items()])

The above accomplishes the same thing, just in a slightly more succinct format. To most programmers that come from a C background, this looks downright odd – kind of like comparing English to Old English. Looks similar but not.

Leave a Reply