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

如何用Jinja2优雅实现嵌套字典的扁平化键值对输出?

Flatten Nested Dictionaries to Dot-Separated Key-Value Pairs in Jinja2

Absolutely! You can achieve this cleanly with a recursive Jinja2 macro that handles arbitrary nesting depth. Here's a concise, elegant solution:

Step 1: Define the Recursive Macro

First, create a macro that traverses the nested dictionary, builds dot-separated keys, and collects key-value strings. This uses Jinja's do extension (required for modifying lists inline):

{% macro flatten_dict(data, prefix='') %}
    {% set key_value_pairs = [] %}
    {% for key, value in data.items() %}
        {% set current_key = prefix ~ key if prefix else key %}
        {% if value is mapping %}
            {% do key_value_pairs.extend(flatten_dict(value, current_key ~ '.')) %}
        {% else %}
            {% do key_value_pairs.append(current_key ~ ':' ~ value) %}
        {% endif %}
    {% endfor %}
    {{ key_value_pairs }}
{% endmacro %}

Step 2: Use the Macro

Call the macro with your nested dictionary, then join the resulting list into a single line with commas:

{% set my_dict = {
    "name": "baggagescreen",
    "favorite": {
        "color": "red",
        "car": {
            "make": "hyundai",
            "model": "sonata",
            "color": "green",
            "year": "1998"
        }
    }
} %}

{{ flatten_dict(my_dict) | join(', ') }}

Output

This will produce exactly the format you want:

name:baggagescreen, favorite.color:red, favorite.car.make:hyundai, favorite.car.model:sonata, favorite.car.color:green, favorite.car.year:1998

Notes

  • Enable the do extension: Jinja2 doesn't include this by default. You'll need to enable it in your environment setup. For example, in Python:
    from jinja2 import Environment, FileSystemLoader
    env = Environment(loader=FileSystemLoader('./'), extensions=['jinja2.ext.do'])
    
  • Handles arbitrary depth: The recursion will keep traversing nested dictionaries no matter how deep they go.
  • Clean and maintainable: The macro logic is straightforward—no redundant code, just a single recursive loop.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:19:36