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

如何在Jinja2中用嵌套字典生成指定格式的表格?

在Jinja2中实现嵌套字典的指定表格样式

完全可以实现,先看你原代码的核心问题:循环层级混乱,{% for k1 in dict.keys() %}的闭合位置错误,导致每个顶层key都生成了独立的行,同时没有将子键和值整合到对应顶层key的单元格内,才会破坏布局。

下面是两种可行的实现方式,分别对应HTML表格和Markdown表格:

方式一:渲染HTML表格

<table border="1">
    <!-- 顶层表头行 -->
    <tr>
        {% for top_key in dict %}
        <th>{{ top_key }}</th>
        {% endfor %}
    </tr>
    <!-- 子表头行 -->
    <tr>
        {% for top_key in dict %}
        <td>
            {% for sub_key in dict[top_key] %}
                {{ sub_key }}{% if not loop.last %} | {% endif %}
            {% endfor %}
        </td>
        {% endfor %}
    </tr>
    <!-- 分隔线行 -->
    <tr>
        {% for top_key in dict %}
        <td style="border-bottom: 1px solid #ccc; height: 2px;"></td>
        {% endfor %}
    </tr>
    <!-- 数值行 -->
    <tr>
        {% for top_key in dict %}
        <td>
            {% for value in dict[top_key].values() %}
                {{ value }}{% if not loop.last %} | {% endif %}
            {% endfor %}
        </td>
        {% endfor %}
    </tr>
</table>

方式二:渲染Markdown格式表格

如果你需要输出Markdown风格的表格,用这段Jinja2代码:

| {% for top_key in dict %}{{ top_key.ljust(10) }} | {% endfor %}
| {% for top_key in dict %}{{ '-' * 10 }} | {% endfor %}
| {% for top_key in dict %}{% for sub_key in dict[top_key] %}{{ sub_key }}{% if not loop.last %} | {% endif %}{% endfor %}  | {% endfor %}
| {% for top_key in dict %}{{ '-' * 10 }} | {% endfor %}
| {% for top_key in dict %}{% for value in dict[top_key].values() %}{{ value }}{% if not loop.last %} | {% endif %}{% endfor %}  | {% endfor %}

核心逻辑说明

  1. 按行构建表格:整个表格分为4行(顶层表头、子表头、分隔线、数值),每行内循环所有顶层key,生成对应单元格
  2. 单元格内拼接内容:每个顶层key对应的单元格里,循环其子键/值,用|分隔,通过loop.last判断是否需要添加分隔符,避免末尾多余符号
  3. 保持字典结构:全程不需要修改原嵌套字典的结构,直接按层级循环即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:35:20