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

如何在Jinja中从动态字典提取键值到独立变量x和y

在Jinja中从指定字典提取目标变量

给定字典结构

FullList = {
    1234: [{"Key": "CI", "Value": "blah"}],
    5678: [{"Key": "CI", "Value": "blah-blah"}]
}

提取变量x和y的方法

方法一:按字典顺序取第一个键值对(适用于1234是第一个键的情况)

直接通过过滤器和字典操作获取:

{# 定义x为字典的第一个键 #}
{% set x = FullList.keys() | first %}
{# 定义y为x对应列表中第一个字典的Value #}
{% set y = FullList[x][0].Value %}

{# 验证输出 #}
x的值:{{ x }}
y的值:{{ y }}

方法二:按Value值匹配提取(适用于不确定1234位置的情况)

通过遍历字典匹配目标Value,获取对应的键和值:

{# 初始化变量 #}
{% set x = None %}
{% set y = None %}

{# 遍历字典的键值对 #}
{% for key, item_list in FullList.items() %}
    {% if item_list[0].Value == "blah" %}
        {% set x = key %}
        {% set y = item_list[0].Value %}
    {% endif %}
{% endfor %}

{# 验证输出 #}
x的值:{{ x }}
y的值:{{ y }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:53:17