Last active
June 9, 2019 22:53
-
-
Save hatarist/cc9aaa63c78061896ceabfd903d91428 to your computer and use it in GitHub Desktop.
Formats a list of dictionaries as a fancy psqlish-style 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 ppprint(data, fields=None, precision=2): | |
""" | |
P-P-PRETTY PRINTER! | |
>>> ppprint([{"foo": 1.2, "bar": "beer"}, {"foo": "bazzzzz", "bar": "bad"}]) | |
""" | |
if fields is None: | |
fields = list(data[0].keys()) | |
formatted_fields = [] | |
for row in data: | |
for field in fields: | |
if isinstance(row[field], float): | |
row[field] = '%.2f' % row[field] | |
widths = [ | |
max( | |
[len(field)] + [len(str(row[field])) for row in data] | |
) | |
for field in fields | |
] | |
row_str = ' ' + ' | '.join('{:>%s}' % width for width in widths) | |
result = row_str.format(*fields) + '\n' | |
result += '+'.join(('-' * (width + 2)) for width in widths) + '\n' | |
result += '\n'.join( | |
row_str.format(*cell) for cell in [[row[field] for field in fields] for row in data] | |
) | |
print(result) | |
if __name__ == '__main__': | |
ppprint([ | |
{"foo": 1.2, "bar": "beer"}, | |
{"foo": "bazzzzz", "bar": "bad"} | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment