如何用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
doextension: 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
相关产品推荐
相关产品推荐

