Skip to content

Instantly share code, notes, and snippets.

@mijdavis2
Last active February 17, 2019 14:57
Show Gist options
  • Save mijdavis2/64af7ba058ff4a0f78a046667330e89d to your computer and use it in GitHub Desktop.
Save mijdavis2/64af7ba058ff4a0f78a046667330e89d to your computer and use it in GitHub Desktop.
Print a table from a list of dictionaries
def print_table(data, column_order=None):
""" Pretty print a list of dictionaries (data) as a dynamically sized table.
If column names (column_order) aren't specified, they will show in random order.
Author: Thierry Husson - Use it as you want but don't blame me.
Source: https://stackoverflow.com/questions/17330139/python-printing-a-dictionary-as-a-horizontal-table-with-headers
PEP8ed by: mijdavis2
"""
if not column_order:
column_order = list(data[0].keys() if data else [])
l = [column_order] # 1st row = header
for item in data:
l.append([str(item[col] or '') for col in column_order])
column_size = [max(map(len, col)) for col in zip(*l)]
formatStr = ' | '.join(["{{:<{}}}".format(i) for i in column_size])
l.insert(1, ['-' * i for i in column_size]) # Seperating line
for item in l:
print(formatStr.format(*item))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment