Pretty printing a list in a tabular format

11,654

Solution 1

mylist = [ ( ('12', '47', '4', '574862', '58', '7856'), 'AGGREGATE_VALUE1'),
           ( ('2', '75', '757', '8233', '838', '47775272785'), 'AGGREG2'),
           ( ('4144', '78', '78965', '778', '78578', '2'), 'AGGREGATE_VALUE3')]

longg = dict.fromkeys((0,1,2,3,4,5,6),0)

for tu,x in mylist:
    for i,el in enumerate(tu):
        longg[i] = max(longg[i],len(str(el)))
    longg[6] = max(longg[6],len(str(x)))

fofo = '  '.join('%'+str(longg[i])+'s' for i in xrange(0,7))
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

result

  12  47      4  574862     58         7856  AGGREGATE_VALUE1
   2  75    757    8233    838  47775272785           AGGREG2
4144  78  78965     778  78578            2  AGGREGATE_VALUE3

Don't know if this fills your need

EDIT 1

Using string formatting with modulo operator (%) to print in a constant length, '%6s' right-justifies in a constant length of 6, and '%-6s' left-justifies in a constant length of 6.

You'll find precisions here

But there is no sense to specify a constant length to print something at the end of a string, because it's somewhat naturally-left-justified in this case. Then :

longg = dict.fromkeys((0,1,2,3,4,5,),0)

for tu,x in mylist:
    for i,el in enumerate(tu):
        longg[i] = max(longg[i],len(str(el)))

fofo = '  '.join('%'+str(longg[i])+'s' for i in xrange(0,6)) + '  %s'
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

EDIT 2

mylist = [ ( (12, 47, 4, 574862, 58, 7856), 'AGGREGATE_VALUE1'),
           ( (2, 75, 757, 8233, 838, 47775272785), 'AGGREG2'),
           ( (4144, 78, 78965, 778, 78578, 2), 'AGGREGATE_VALUE3')]

longg = dict.fromkeys((0,1,2,3,4,5),0)

for tu,_ in mylist:
    longg.update(( i, max(longg[i],len(str(el))) ) for i,el in enumerate(tu))

fofo = '  '.join('%%%ss' % longg[i] for i in xrange(0,6)) + '  %s'
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

EDIT 3

mylist = [ ( (12, 47, 4, 574862, 58, 7856), 'AGGREGATE_VALUE1'),
           ( (2, 75, 757, 8233, 838, 47775272785), 'AGGREG2'),
           ( (4144, 78, 78965, 778, 78578, 2), 'AGGREGATE_VALUE3')]

header = ('Price1','Price2','reference','XYD','code','resp','AGGREG values')

longg = dict(zip((0,1,2,3,4,5,6),(len(str(x)) for x in header)))

for tu,x in mylist:
    longg.update(( i, max(longg[i],len(str(el))) ) for i,el in enumerate(tu))
    longg[6] = max(longg[6],len(str(x)))
fofo = ' | '.join('%%-%ss' % longg[i] for i in xrange(0,7))

print '\n'.join((fofo % header,
                 '-|-'.join( longg[i]*'-' for i in xrange(7)),
                 '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)))

result

Price1 | Price2 | reference | XYD    | code  | resp        | AGGREG values   
-------|--------|-----------|--------|-------|-------------|-----------------
12     | 47     | 4         | 574862 | 58    | 7856        | AGGREGATE_VALUE1
2      | 75     | 757       | 8233   | 838   | 47775272785 | AGGREG2         
4144   | 78     | 78965     | 778    | 78578 | 2           | AGGREGATE_VALUE3

Note that this kind of formatting would be much easier with the string's method format() introduced in Python 2.6

Solution 2

Try the texttable module.

Docs: http://foutaise.org/code/texttable/

PyPi: https://pypi.python.org/pypi?name=texttable&:action=display

Solution 3

Maybe something like this:

def tabprint(inp):
    for list_el in mylist:
        st = ''
        for word in list_el[0]:
            st += word + '\t' 
        st += str(list_el[1])

    print st
Share:
11,654
GPX
Author by

GPX

Updated on June 04, 2022

Comments

  • GPX
    GPX about 2 years

    Using Python 2.4, how do I print a list in a nice tabular format?

    My list is in the below format.

    mylist=[(('VAL1', 'VAL2', 'VAL3', 'VAL4', 'VAL5', 'VAL6'), AGGREGATE_VALUE)]
    

    I have tried pprint, but it does not print the result in a tabular format.

    EDIT : I would like to see the output in the below format:


    VAL1        VAL2     VAL3    VAL4    VAL5    VAL6        AGGREGATE_VALUE


    This table, should account for variable item lengths and still print with proper indentation.

    • Pradeep Nayak
      Pradeep Nayak about 13 years
      This is a little unclear. Could you please paste a line of Output?
    • Rob Cowie
      Rob Cowie about 13 years
      Do you want to see a table in your console? or do you intend to output to some other target, say html?
    • johnsyweb
      johnsyweb about 13 years
      Sample data and expectout output would be a huge help to those who want to help!
    • Rob Cowie
      Rob Cowie about 13 years
  • Thomas Wouters
    Thomas Wouters about 13 years
    '\t'.join() is a better thing to use than manual string building.
  • GPX
    GPX about 13 years
    This is exactly what I was looking for! But how do I left-align all the text?
  • GPX
    GPX about 13 years
    This does work, but does not account for varying string lengths.
  • GPX
    GPX about 13 years
    I just tried Edit 1 and it prints out the same right-aligned output! Also, how do I print a header row?
  • GPX
    GPX about 13 years
    Edit 2 gives the same result :-( However, both Edit 1 & 2 gave a left-aligned last column.
  • eyquem
    eyquem about 13 years
    I didn't understand your question: I thought that speaking of 'all the text', you were speaking of the texts 'AGGREGATE_VALUE1' etc. I still don't understand what you mean by 'left-align all the text'. Do you mean that you want to justify each value of a column at the left of the column ? If so, you must replace '%%%ss' with '%%-%ss' . By the way, Edit 2 wasn't to answer to your comment, it is an improvement
  • GPX
    GPX about 13 years
    Ah yes! %%-%ss did the trick. Yes, I did mean justifying each column value to the left.
  • eyquem
    eyquem about 13 years
    To print a header row, put its values as first element in mylist, with same format as the other elements. For exemple : mylist.insert(0,(('Price1','Price2','reference','XYD','code'‌​,'resp'),'AGGREG values'))
  • GPX
    GPX about 13 years
    Yup, figured that out. After I'm done with printing it, I remove it using del mylist[0].
  • eyquem
    eyquem about 13 years
    Many diverse solutions can be proposed according the data before the treatment. In Edit 3, I give an exemple of what can be done without including the header in the list. This exemple may not be useful for your particular data, but it gives ideas, I think.