Skip to content

Commit

Permalink
minor tweaks to print_dict_table
Browse files Browse the repository at this point in the history
  • Loading branch information
dantownsend committed Jan 22, 2024
1 parent c0f0ba3 commit 662549d
Showing 1 changed file with 21 additions and 13 deletions.
34 changes: 21 additions & 13 deletions piccolo/utils/printing.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import List


def get_fixed_length_string(string: str, length=20) -> str:
def get_fixed_length_string(string: str, length: int = 20) -> str:
"""
Add spacing to the end of the string so it's a fixed length, or truncate
if it's too long.
Expand All @@ -24,26 +24,34 @@ def print_heading(string: str, width: int = 64) -> None:
def print_dict_table(data: List[dict], header_separator: bool = False) -> None:
"""
Prints out a list of dictionaries in tabular form.
Uses the first list element to extract the
column names and their order within the row.
Uses the first list element to extract the column names and their order
within the row.
"""
ref_order = [column for column in data[0]]
width = {column: len(str(column)) for column in ref_order}
if len(data) == 0:
raise ValueError("The data must have at least one element.")

column_names = data[0].keys()
widths = {column_name: len(column_name) for column_name in column_names}

for item in data:
for column in ref_order:
if len(str(item[column])) > width[column]:
width[column] = len(str(item[column]))
for column in column_names:
width = len(str(item[column]))
if width > widths[column]:
widths[column] = width

format_string = " | ".join([f"{{:<{width[w]}}}" for w in ref_order])
format_string = " | ".join(f"{{:<{widths[w]}}}" for w in column_names)

print(format_string.format(*[str(w) for w in ref_order]))
print(format_string.format(*[str(w) for w in column_names]))

if header_separator:
format_string_sep = "-+-".join(
[f"{{:<{width[w]}}}" for w in ref_order]
[f"{{:<{widths[w]}}}" for w in column_names]
)
print(
format_string_sep.format(*["-" * widths[w] for w in column_names])
)
print(format_string_sep.format(*["-" * width[w] for w in ref_order]))

for item in data:
print(format_string.format(*[str(item[w]) for w in ref_order]))
print(format_string.format(*[str(item[w]) for w in column_names]))

0 comments on commit 662549d

Please sign in to comment.