Skip to content

Instantly share code, notes, and snippets.

@SpoopyTim
Last active March 14, 2022 23:48
Show Gist options
  • Save SpoopyTim/982c2629799125eb719dcf5389daba37 to your computer and use it in GitHub Desktop.
Save SpoopyTim/982c2629799125eb719dcf5389daba37 to your computer and use it in GitHub Desktop.
Colored Dictionary Tables
import colorama
from tabulate import tabulate
from pandas import DataFrame, json_normalize
from typing import MutableMapping
class ColorTables:
def __init__(self, init_colorama: bool = False):
if init_colorama:
colorama.init()
def _flatten(self, d: MutableMapping) -> MutableMapping:
return json_normalize(d, sep=self.key_seperator).to_dict(orient="records")
def write(
self,
box_color: colorama.Fore,
text_color: colorama.Fore,
data: dict,
key_seperator: str = ".",
headers: list = (),
header_color: colorama.Fore = None
) -> str:
"""Generates a colored table.
Args:
box_color (colorama.Fore): The color to use for drawing the box.
text_color (colorama.Fore): The color to use for text.
data (dict): The data to represent in the the table.
key_seperator (str): The seperator used when flattening dictionary items.
headers (list, optional): The headers to use for the table. Defaults to ().
header_color (colorama.Fore, optional): The color to use for the header. If not specified defaults to None and text_color is used instead.
Returns:
str: The output of the generator.
Example Usage:
data = {"name": "Mike", "occupation": "Network Engineer", "experience": {"years": 3, "jobs": ["Job 1", "Job 2"]}}
headers = ["Header 1", "Header 2", "Header 3", "Header 4"]
box_color = colorama.Fore.GREEN
text_color = colorama.Fore.RED
header_color = colorama.Fore.CYAN
"""
df = DataFrame(self._flatten(data))
output = str(tabulate(df.T, tablefmt="fancy_grid", headers=headers))
i = 0
final: str = ""
for line in output.split("\n"):
if i / 2 == 0.5:
final += line.replace("│", box_color + "│" + header_color if header_color is not None else text_color) + "\n"
else:
final += line.replace("│", box_color + "│" + text_color) + "\n"
i += 1
return final
def write_from_list(
self,
box_color: colorama.Fore,
text_color: colorama.Fore,
data: list,
headers: list = (),
header_color: colorama.Fore = None
) -> str:
"""Generates a colored table.
Args:
box_color (colorama.Fore): The color to use for drawing the box.
text_color (colorama.Fore): The color to use for text.
data (list): The data to represent in the the table. Uses a 2 dimensional array format to represent rows and columns.
headers (list, optional): The headers to use for the table. Defaults to ().
header_color (colorama.Fore, optional): The color to use for the header. If not specified defaults to None and text_color is used instead.
Returns:
str: The output of the generator.
Example Usage:
data = [["Row 1", "Col 2", "Col 3", "Col 4"], ["Row 2", "Col 2", "Col 3", "Col 4"], [3, "Col 2", "Col 3", "Col 4"], ["Row 4", "Col 2", "Col 3", "Col 4"]]
headers = ["Header 1", "Header 2", "Header 3", "Header 4"]
box_color = colorama.Fore.GREEN
text_color = colorama.Fore.RED
header_color = colorama.Fore.CYAN
"""
output = str(tabulate(data, tablefmt="fancy_grid", headers=headers))
i = 0
final: str = ""
for line in output.split("\n"):
if i % 2 == 0:
final += box_color + line + colorama.Fore.RESET + "\n"
else:
if i / 2 == 0.5:
final += line.replace("│", box_color + "│" + header_color if header_color is not None else text_color) + "\n"
else:
final += line.replace("│", box_color + "│" + text_color) + "\n"
i += 1
return final
from colortables import ColorTables
import colorama
table_generator = ColorTables(init_colorama=True)
# Dictionary Usage (Recommended)
data = {
"name": "NAME",
"token": "TOKEN",
"storage": {
"database": {
"enabled": False,
"auto_sync": True
},
"documents": {
"enabled": True,
"use_backend": False
}
}
}
out = table_generator.write(box_color=colorama.Fore.GREEN, text_color=colorama.Fore.CYAN, data=data, key_seperator=".", headers=["Header 1", "Header2", "Header 3"], header_color=colorama.Fore.GREEN)
print(out)
# 2D Array Usage
items = [["Item 1", "Description", "True"], ["Item 2", "No description", "False"], ["Item 3", "N/A", "True"]]
out = table_generator.write_from_list(colorama.Fore.RED, colorama.Fore.CYAN, data=items, headers=["Header 1", "Header2", "Header 3"], header_color=colorama.Fore.GREEN)
print(out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment