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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Deriving columns from the data keeps the function usable without an explicit schema.
- 2Computing per-column widths up front lets every row align consistently.
- 3Small local helpers for formatting and padding keep the assembly logic readable.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/rendering-an-aligned-markdown-table-in-python-explained-python-8904/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.