11

What's the best way to print tabular data in Python? Say the data is in a 2D list and I want to create a smart looking table. What I actually have is a list of dictionaries and I want to print an intersection depending on values in the dictionaries. Something like

for val1 in my_dict:
   for val2 in my_dict:
    if val1['a'] > val2['a']:
      print 'x'

but in such a way that each column is fixed width. Writter and formatter classes seem like something in the realm of possibility, but still look complex to use when compared to, say, Perl's formatter.

Are there any existing implementations or do I have to write my own?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Makis
  • 12,468
  • 10
  • 62
  • 71
  • I think you might want to try pprint (yes, two 'p's). I don't use it but I've seen others use it in similar situations and hence it rings a bell here – inspectorG4dget Feb 25 '11 at 20:47
  • I have looked at pprint, but I can't see how to use it in the way I need to. – Makis Feb 25 '11 at 21:24
  • 2
    The possible duplicate has more votes and answers: http://stackoverflow.com/questions/9535954/python-printing-lists-as-tabular-data. Always give explicit desired output examples =) – Ciro Santilli OurBigBook.com Mar 25 '14 at 11:13
  • Possible duplicate of [How can I pretty-print ASCII tables with Python?](https://stackoverflow.com/questions/5909873/how-can-i-pretty-print-ascii-tables-with-python) – ivan_pozdeev Jul 18 '18 at 18:51
  • Does this answer your question? [Printing Lists as Tabular Data](https://stackoverflow.com/questions/9535954/printing-lists-as-tabular-data) – Gino Mempin Dec 03 '22 at 03:29

3 Answers3

15
print "%20s" % somevar 

Will print the value 'somevar' and use up to 20 spaces. Add a comma behind the print statement in order to avoid the line-break - and of course: read the string formatting operations docs on the '%' operator

Jujhar Singh
  • 3,641
  • 5
  • 29
  • 38
9

Do you know about PyPi?

DataGrid and PrettyTable seem like two good alternatives I found with a brief search. You may have to assemble the data in the format you want it (with "x" for when your condition is true) before sending it to the routines provided.

Hut8
  • 6,080
  • 4
  • 42
  • 59
6

Here are two ways to write a table of squares and cubes:

for x in range(1, 11):
    print repr(x).rjust(2), repr(x*x).rjust(3),print repr(x*x*x).rjust(4)

for x in range(1,11):
    print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)

Check this for details.

imsc
  • 7,492
  • 7
  • 47
  • 69