You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python无第三方库实现嵌套字典的对齐表格打印

解决方案:原生Python实现嵌套字典转对齐表格

针对你的环境限制(仅Python 3.7.3原生功能,无第三方库),可以通过计算列宽+字符串格式化的方式实现规整对齐的表格打印,具体代码如下:

all_dicts = {
     'dict_0': {'Author(s)': 'Ian Flemming', 'Year': '1956', 'Title': 'Diamonds are Forever', 'surname': 'Flemming', 'ISBN Number will go here': '9781612185460'},
     'dict_1': {'Author(s)': 'Jules Verne', 'Year': '1870', 'Title': '20,000 Leagues Under the Sea', 'surname': 'Verne', 'ISBN Number will go here': '0451531698'}
}

# 提取列标题(子字典名称)和行键(子字典的键)
col_titles = list(all_dicts.keys())
row_keys = list(next(iter(all_dicts.values())).keys())

# 美化行标签(匹配示例中的显示格式)
def format_row_label(key):
    if key == 'Author(s)':
        return 'Authors'
    return key.capitalize()

row_labels = [format_row_label(k) for k in row_keys]

# 计算每列的最大宽度(确保能容纳最长内容)
# 第一列(行标签列)的宽度
first_col_width = max(len(label) for label in row_labels)
# 数据列的宽度:列标题+对应列所有值的最长长度
data_col_widths = []
for title in col_titles:
    max_len = len(title)
    for val in all_dicts[title].values():
        if len(val) > max_len:
            max_len = len(val)
    data_col_widths.append(max_len)

# 打印表头行
header = f"{'':<{first_col_width}}"
for title, width in zip(col_titles, data_col_widths):
    header += f" {title:<{width}}"
print(header)

# 打印每一行数据
for label, key in zip(row_labels, row_keys):
    line = f"{label:<{first_col_width}}"
    for title, width in zip(col_titles, data_col_widths):
        line += f" {all_dicts[title][key]:<{width}}"
    print(line)

关键逻辑说明

  1. 列宽计算:先统计每一列所有内容(包括标题和值)的最长长度,确保列宽足够容纳所有内容,避免对齐错位。
  2. 键名美化:根据示例需求将Author(s)转为Authors、surname转为Surname,可通过修改format_row_label函数调整其他键的显示。
  3. 左对齐格式化:使用Python字符串格式化的<标记实现左对齐,保证所有内容沿列左侧对齐,和示例效果一致。
  4. 原生依赖:仅使用内置的字典、列表操作和字符串格式化,完全符合你的运行环境要求。

输出效果

dict_0                 dict_1
Authors              Ian Flemming           Jules Verne
Year                 1956                   1870
Title                Diamonds are Forever   20,000 Leagues Under the Sea
Surname              Flemming               Verne
ISBN Number will go here 9781612185460          0451531698

内容的提问来源于stack exchange,提问作者DevNull

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:41:13