python 57 lines · 8 steps

Rendering an aligned Markdown table in Python

A single function turns a list of dict rows into a neatly column-aligned Markdown table.

Explained by highlit
1from typing import Any, Sequence, Mapping
2 
3 
4def render_markdown_table(
5 rows: Sequence[Mapping[str, Any]],
6 columns: Sequence[str] | None = None,
7 align: Mapping[str, str] | None = None,
8) -> str:
9 if columns is None:
10 columns = list(dict.fromkeys(k for row in rows for k in row))
11 align = align or {}
12 
13 def fmt(value: Any) -> str:
14 if value is None:
15 return ""
16 if isinstance(value, bool):
17 return "yes" if value else "no"
18 if isinstance(value, float):
19 return f"{value:g}"
20 return str(value)
21 
22 table = [[fmt(row.get(col)) for col in columns] for row in rows]
23 widths = [
24 max(len(col), *(len(cell[i]) for cell in table)) if table else len(col)
25 for i, col in enumerate(columns)
26 ]
27 
28 def pad(text: str, width: int, how: str) -> str:
29 if how == "right":
30 return text.rjust(width)
31 if how == "center":
32 return text.center(width)
33 return text.ljust(width)
34 
35 def divider(width: int, how: str) -> str:
36 if how == "center":
37 return ":" + "-" * max(1, width - 2) + ":"
38 if how == "right":
39 return "-" * max(1, width - 1) + ":"
40 if how == "left":
41 return ":" + "-" * max(1, width - 1)
42 return "-" * width
43 
44 header = "| " + " | ".join(
45 pad(col, widths[i], align.get(col, "left")) for i, col in enumerate(columns)
46 ) + " |"
47 separator = "| " + " | ".join(
48 divider(widths[i], align.get(col, "left")) for i, col in enumerate(columns)
49 ) + " |"
50 body = [
51 "| " + " | ".join(
52 pad(cell[i], widths[i], align.get(col, "left"))
53 for i, col in enumerate(columns)
54 ) + " |"
55 for cell in table
56 ]
57 return "\n".join([header, separator, *body])
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Deriving columns from the data keeps the function usable without an explicit schema.
  2. 2Computing per-column widths up front lets every row align consistently.
  3. 3Small local helpers for formatting and padding keep the assembly logic readable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Rendering an aligned Markdown table in Python — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code