[Tutor] Pulling items from a dict in a print command
Danny Yoo
dyoo at hashcollision.org
Thu Jun 19 03:51:27 CEST 2014
Hi Ben,
There's a bit of duplication in the keys being looked up, making it a
bit fragile if you need to correct the spelling of a key or need to
add additional keys, since there are two places that need to be
changed.
One way to make this a little cleaner might be to have a helper
function that does the work you're doing now in constructing the
formatting string. Something like this might be worth it:
################################################
def makeStatusLine(keyValues, firstKey, restKeys):
buffer = []
for key in restKeys:
buffer.append("%s=%s" % (key, keyValues[key]))
firstColumn = "%s=%s|" % (firstKey, keyValues[firstKey])
return firstColumn + ",".join(buffer)
################################################
For example:
################################################
>>> makeStatusLine({'name': 'Ben', 'forum': 'tutor at python.org'}, 'name', ['forum'])
'name=Ben|forum=tutor at python.org'
################################################
That way, you can write the sequence of columns just once, and be a
lot more sure that the output is formatted consistently. Here, we'll
know the first column is treated specially with the "|" pipe symbol,
and the rest will be comma-delimited.
More information about the Tutor
mailing list