Created
April 17, 2019 14:22
-
-
Save danggrianto/e756bfd32a713731c9e21a23cea7f6e9 to your computer and use it in GitHub Desktop.
Print Table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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