[Tutor] print formatting, length of string

Lloyd Kvam pythonTutor at venix.com
Mon Jun 28 14:24:35 EDT 2004


(complete this time.  Earlier email was sent by accident.)

<Totally untested, but (hopefully) close>
def formatListOfRecordDicts(listOfRecordDicts, showKeyList=None):
	if showKeyList is None:
		showKeyList = listOfRecordDicts[0].keys() # fails on empty list
	keylen = max([len(k) for k in showKeyList])
	for i,recordDict in enumerate(listOfRecordDicts):
		print "**** %s. row *****" % (i+1)
		for k in showKeyList:
			print "%*s: %s" % (keylen, k, recordDict[k])


Choosing the keys to print is now outside the function
enumerate is used to count the dictionaries in the list
the key list is scanned to determine the longest key
The format operator is used to control the output width



On Mon, 2004-06-28 at 13:40, tpc at csua.berkeley.edu wrote:

> <code>
> 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']
> </code>
> 
> 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 ?
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582




More information about the Tutor mailing list