[Tutor] print formatting, length of string

tpc at csua.berkeley.edu tpc at csua.berkeley.edu
Mon Jun 28 13:40:05 EDT 2004

hi everybody,
let's say I have a list of dictionaries, and each dictionary, representing
a database record, stores a series of key, value pairs, and I want to
print out each key, value pair such that:
*) each key ends with ': '
*) the length of the longest key determines how many spaces prepend the
shorter keys, e.g.,:

*************************** 1. row ***************************
   First_Name: JAMES
    Last_Name: SMITH
Address_Line1: 2525 BANTRY LANE
         City: NORTH BRUNSWICK
        State: NJ
*************************** 2. row ***************************
   First_Name: MARY
    Last_Name: JONES
Address_Line1: 1713 RIVER CREEK RD
         City: PALM HARBOR
        State: FL

In other words, I want my colons to line up.  The code I have so far is a

def formatListOfRecordDicts(listOfRecordDicts):
        count = 0
        for recordDict in listOfRecordDicts:
                count += 1
                print "*************************** % s. row ***************************" % count
                print "   First_Name:", recordDict['First_Name']
                print "    Last_Name:", recordDict['Last_Name']
                print "Address_Line1:", recordDict['Address_Line1']

and as you can imagine I'd have to rewrite it if and when I decide to pull
out a different set of data from my database.  Is there a more elegant way
of doing this ?

More information about the Tutor mailing list