[Tutor] Formatting output into columns

Kent Johnson kent37 at tds.net
Thu Aug 30 23:25:55 CEST 2007


Scott Oertel wrote:
> #!/usr/bin/env python
> 
> data = {}
> lrgColumn = 0
> 
> for line in open("test.txt","r").read().splitlines():
>     char = line[0].lower()
>     if not char in data:
>         data[char] = [line]
>     else:
>         data[char].append(line)

I like
   data.setdefault(char, []).append(line)
instead of the four lines above.

> 
> for item in data:
>     print item.ljust(10),
>     if len(data[item]) > lrgColumn:
>         lrgColumn = len(data[item])
> print
> 
> for item in range(lrgColumn):
>     for i in data.iteritems():
>         try:
>             print i[1][item].ljust(10),

If you used data.itervalues() then it would be just
   print i[item].ljust(10),

>         except IndexError:
>             print "".ljust(10),
>     print

To get the data in row order you can use
   map(None, *data.values())
This will give a list of rows with None in the blank spots.

You might like one of these recipes for the actual table output:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/519618

Kent


More information about the Tutor mailing list