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

如何从包含重复列名的Python字典列表生成HTML表格

列表嵌套单键字典转HTML表格实现方法

核心逻辑说明

你提供的数据集存在固定规律:所有单键字典按id→e→i的顺序循环排列,每3个连续字典对应表格的一行数据。我们只需要先将一维列表按步长3拆分分组,每组合并为完整的行数据,再拼接HTML标签即可。

完整Python实现代码

# 源数据
raw_data = [{'id': 1}, {'e': 2}, {'i': 3}, {'id': 12}, {'e': 12}, {'i': 23},
            {'id': 13}, {'e': 3}, {'i': None}, {'id': 14}, {'e': 23},
            {'i': None}, {'id': 123}, {'e': 123}, {'i': 123}]

# 1. 数据分组合并,每3个单键字典合并为一行数据
table_rows = []
for idx in range(0, len(raw_data), 3):
    # 取连续3个字典合并为单行
    current_row = {}
    for item in raw_data[idx: idx+3]:
        current_row.update(item)
    table_rows.append(current_row)

# 2. 拼接HTML表格代码
html_table = """<table border="1">
  <thead>
    <tr>
      <th>id</th>
      <th>e</th>
      <th>i</th>
    </tr>
  </thead>
  <tbody>
"""
for row in table_rows:
    # 处理None值转为空字符串显示
    i_content = row['i'] if row['i'] is not None else ''
    html_table += f"""    <tr>
      <td>{row['id']}</td>
      <td>{row['e']}</td>
      <td>{i_content}</td>
    </tr>
"""
html_table += """  </tbody>
</table>"""

# 输出结果
print(html_table)

输出效果说明

运行代码后生成的HTML表格渲染后效果如下:

idei
123
121223
133
1423
123123123

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:15:03