Last active
August 4, 2022 09:48
-
-
Save Hansimov/03e142482b89e12a7ec4e7b4ad05beb1 to your computer and use it in GitHub Desktop.
python pretty print a dict
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Color print | |
def color_str(s, level="info"): | |
msg_level_D = { | |
"shell": "1;36;40", # cyan | |
"success": "1;32;40", # green | |
"info": "1;34;40", # blue | |
"warn": "1;35;40", # magenta | |
"error": "1;31;40", # red | |
"hint": "1;33;40", # yellow | |
"mark": "1;37;42", # white + green | |
} | |
cb = "\x1b[{}m" | |
ce = "\x1b[0m" | |
cb = cb.format(msg_level_D[level]) | |
return f"{cb}{s}{ce}" | |
def color_print(s, level="info"): | |
print(color_str(s, level=level)) | |
# Pretty print dict | |
class DictPrettifier: | |
pass | |
def disp_dict(data, indent=4, level=0, indent_key=False, brace=True, max_key_len=0, depth=20, item_idx=True, compact=True, compact_limit=80): | |
if indent_key: | |
max_key_len = len(max(data, key=len)) | |
else: | |
max_key_len = 0 | |
dict_str = "" | |
brace_indent_str = ' '*((level)*indent) | |
if brace: | |
if level>0: | |
dict_str += "\n" | |
dict_str += color_str(f"{brace_indent_str}{{", "warn") | |
if level < 0: | |
indent_str = "" | |
else: | |
indent_str = " " * ((level+1) * indent) | |
if level <= depth-1: | |
for idx, (k, v) in enumerate(data.items()): | |
k_str = color_str(f"{k:{max_key_len+1}}", "warn") | |
if isinstance(v, collections.abc.Mapping): | |
params = get_func_params() | |
params["data"] = v | |
params["level"] += 1 | |
v_str = disp_dict(**params) | |
else: | |
v_str = color_str(f"{v}", "info") | |
colon_str = color_str(":", "hint") | |
dict_str += f"\n{indent_str}{k_str}{colon_str} {v_str}" | |
if brace: | |
dict_str += color_str(f"\n{brace_indent_str}}}", "warn") | |
if level == 0: | |
print(dict_str) | |
else: | |
keys_str = ','.join(data.keys()) | |
if compact and len(keys_str) > compact_limit: | |
keys_str = keys_str[:compact_limit] + "..." | |
keys_num = len(data.keys()) | |
if keys_num < 3: | |
keys_num_str = "" | |
else: | |
keys_num_str = f"({keys_num} items)" | |
dict_str = f"{keys_num_str} {{{keys_str}}}" | |
return dict_str | |
# Pretty print list of dict | |
def disp_dict_list(lst, item_idx=True, **kwargs): | |
for idx, item in enumerate(lst): | |
if item_idx: | |
print(f"\n(Item: {idx+1}/{len(lst)})") | |
dict_str = disp_dict(item, **kwargs) | |
# print(dict_str) | |
# def pprint_dict(d, indent=2, width=80): | |
# pp = pprint.PrettyPrinter(indent=indent) | |
# pp.pprint(d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment