Skip to content

Instantly share code, notes, and snippets.

@hatarist
Last active June 9, 2019 22:53
Show Gist options
  • Save hatarist/cc9aaa63c78061896ceabfd903d91428 to your computer and use it in GitHub Desktop.
Save hatarist/cc9aaa63c78061896ceabfd903d91428 to your computer and use it in GitHub Desktop.
Formats a list of dictionaries as a fancy psqlish-style table.
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