如何从包含重复列名的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表格渲染后效果如下:
| id | e | i |
|---|---|---|
| 1 | 2 | 3 |
| 12 | 12 | 23 |
| 13 | 3 | |
| 14 | 23 | |
| 123 | 123 | 123 |
内容的提问来源于stack exchange,提问作者Haseeb
相关产品推荐
相关产品推荐

