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

Home Assistant模板中JSON键值对的修改与新增问题

Home Assistant模板中字典的修改与新增键值对方案

路径:Home Assistant -> Developer Tools -> Templates

问题描述

在模板编辑器中定义初始字典:

{% set temp = {'a': '1', 'b': 2} %}
{{ temp }}

输出:

{'a': '1', 'b': 2}

需要实现两个操作:

  • 给字典新增键值对,希望无需通过循环创建新字典,优先使用合并类方案,避免字符串处理
  • 修改已有键的值:虽能通过{{ temp.a }}或{{ temp['a'] }}获取值,但直接赋值会报错:
    • 执行{% set temp.a = '2' %},报错:

      TemplateRuntimeError: cannot assign attribute on non-namespace object

    • 执行{% set temp['a'] = '2' %},报错:

      TemplateSyntaxError: expected token 'end of statement block', got '['

解决方案

Jinja2中的字典属于不可变对象,无法直接修改原字典的键值或添加新键,需通过合并字典生成新字典来实现需求:

1. 同时修改已有键值并新增键值对

使用dict()函数合并原字典与新键值:

{% set temp = {'a': '1', 'b': 2} %}
{% set updated_temp = dict(temp, a='2', c='3') %}
{{ updated_temp }}

输出:

{'a': '2', 'b': 2, 'c': '3'}

也可使用字典展开语法,适合处理动态生成的更新内容:

{% set temp = {'a': '1', 'b': 2} %}
{% set updates = {'a': '2', 'c': '3'} %}
{% set updated_temp = {**temp, **updates} %}
{{ updated_temp }}

输出结果与上述一致。

2. 仅新增键值对

只需在合并时传入新键值即可:

{% set temp = {'a': '1', 'b': 2} %}
{% set updated_temp = dict(temp, c='3') %}
{{ updated_temp }}

输出:

{'a': '1', 'b': 2, 'c': '3'}

这种方式无需循环,直接通过合并生成新字典,完全满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:42:56