Skip to content

Instantly share code, notes, and snippets.

@danggrianto
Created April 17, 2019 14:22
Show Gist options
  • Select an option

  • Save danggrianto/e756bfd32a713731c9e21a23cea7f6e9 to your computer and use it in GitHub Desktop.

Select an option

Save danggrianto/e756bfd32a713731c9e21a23cea7f6e9 to your computer and use it in GitHub Desktop.
Print Table
def print_table(my_dict, col_list=None):
""" Pretty print a list of dictionaries (myDict) as a dynamically sized table.
If column names (colList) aren't specified, they will show in random order.
Author: Thierry Husson - Use it as you want but don't blame me.
"""
if not col_list:
col_list = list(my_dict[0].keys() if my_dict else [])
my_list = [col_list] # 1st row = header
for i in my_dict:
my_list.append([str(i[col] or '') for col in col_list])
col_size = [max(map(len, col)) for col in zip(*my_list)]
format_str = ' | '.join(["{{:<{}}}".format(i) for i in col_size])
my_list.insert(1, ['-' * i for i in col_size])
for i in my_list:
print(format_str.format(*i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment