Skip to content

Instantly share code, notes, and snippets.

@SegFaultAX
Created February 26, 2013 20:24
Show Gist options
  • Save SegFaultAX/5041827 to your computer and use it in GitHub Desktop.
Save SegFaultAX/5041827 to your computer and use it in GitHub Desktop.
Formats a list of dicts into a textual table.
#!/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