Python: Print list of dicts as ascii table

Sometimes I want to print list of dicts as an ascii table, like this:

| Programming Language | Language Type | Years of Experience |
+----------------------+---------------+---------------------+
| python               | script        |                   4 |
| php                  | script        |                   5 |
| java                 | compiled      |                  11 |
| assember             | compiled      |                  15 |

I searched on Google - but without luck.

That's what I came up with - it's not particularly nice but it does the job:

PYTHON:
  1. def table_print(data, title_row):
  2.     """data: list of dicts,
  3.        title_row: e.g. [('name', 'Programming Language'), ('type', 'Language Type')]
  4.     """
  5.     max_widths = {}
  6.     data_copy = [dict(title_row)] + list(data)
  7.     for col in data_copy[0].keys():
  8.         max_widths[col] = max([len(str(row[col])) for row in data_copy])
  9.     cols_order = [tup[0] for tup in title_row]
  10.        
  11.     def custom_just(col, value):
  12.         if type(value) == int:
  13.             return str(value).rjust(max_widths[col])
  14.         else:
  15.             return value.ljust(max_widths[col])
  16.    
  17.     for row in data_copy:
  18.         row_str = " | ".join([custom_just(col, row[col]) for col in cols_order])
  19.         print "| %s |" % row_str
  20.         if data_copy.index(row) == 0:
  21.             underline = "-+-".join(['-' * max_widths[col] for col in cols_order])
  22.             print '+-%s-+' % underline

Use it like that:

PYTHON:
  1. data = [dict(name='python', type='script', years_experience=4),
  2.     dict(name='php', type='script', years_experience=5),
  3.     dict(name='java', type='compiled', years_experience=11),
  4.     dict(name='assember', type='compiled', years_experience=15)
  5.     ]
  6. titles = [('name', 'Programming Language'),
  7.     ('type', 'Language Type'),
  8.     ('years_experience', 'Years of Experience')]
  9. table_print(data, titles)

It will produce the table printed above. It's not fancy - the only 'smart' thing it does is right-adjusting integers, strings are left-adjusted.

P.S. no, I don't have 15 years of experience of Assembler - I just know it since 15 years - it's one of the first programming languages I learned - and I even wrote a text editor with it - then I learned that's probably not the best language to write an editor :-)

Leave a Reply