Created
February 26, 2013 20:24
-
-
Save SegFaultAX/5041827 to your computer and use it in GitHub Desktop.
Formats a list of dicts into a textual 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
#!/usr/bin/env python | |
# Ported from clojure.pprint/print-table | |
from StringIO import StringIO | |
def format_row(headers, row, fmts): | |
out = [] | |
for col, fmt in zip([row[k] for k in headers], fmts): | |
out.append(fmt % col) | |
return " | ".join(out) | |
def table(rows, headers=None): | |
if headers is None: | |
headers = rows[0].keys() | |
widths = [max(len(str(k)), *[len(str(r[k])) for r in rows]) for k in headers] | |
fmts = [''.join(["%-", str(w), "s"]) for w in widths] | |
header = format_row(headers, dict(zip(headers, headers)), fmts) | |
bar = "=" * len(header) | |
buffer = StringIO() | |
buffer.write(bar + "\n") | |
buffer.write(header + "\n") | |
buffer.write(bar + "\n") | |
for row in rows: | |
buffer.write(format_row(headers, row, fmts) + "\n") | |
buffer.write(bar) | |
return buffer.getvalue() | |
if __name__ == "__main__": | |
print "== Example ==\n" | |
data = [ | |
{ "name": "John", "age": 25 }, | |
{ "name": "Michael", "age": 30}, | |
{ "name": "Jim", "age": 16 } | |
] | |
print table(data, headers=["name", "age"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment