Python 使用jinja2时如何将新条目添加到字典对象中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36886650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:30:03  来源:igfitidea点击:

How to add a new entry into a dictionary object while using jinja2?

pythondictionaryjinja2

提问by hemant_maverik

I am not able to append add a new entry into a dictionary object while using jinja2 template.

使用 jinja2 模板时,我无法将新条目添加到字典对象中。

For example, here I am using jinja2 template and I have created a datavariable which is a dictionary. And after checking some ifcondition I WANTto append location attribute to the data object e.g.

例如,这里我使用的是 jinja2 模板,我创建了一个数据变量,它是一个字典。并检查一些后,如果条件我WANT到位置属性附加到数据对象如

{%- set data = {
                  'name' : node.Name,
                  'id' : node.id,
               }
-%}

{% if node.location !="" %}
    data.append({'location': node.location}) 
{% endif %}

However I could not find a way to achieve this and am getting the UndefinedError:

但是,我找不到实现此目的的方法,并且收到了 UndefinedError:

jinja2.exceptions.UndefinedError: 'dict object' has no attribute 'append'

Has anyone faced this issue or could provide a reference to solve this?

有没有人遇到过这个问题或可以提供参考来解决这个问题?

I searched the web but could not find a solution i.e. how to achieve adding an entry to the dict object in the Jinja.

我在网上搜索,但找不到解决方案,即如何实现向 Jinja 中的 dict 对象添加条目。

I have referred following and other web resources:

我参考了以下和其他网络资源:

  1. http://cewing.github.io/training.codefellows/assignments/day22/jinja2_walkthrough.html
  2. In Jinja2 whats the easiest way to set all the keys to be the values of a dictionary?
  3. https://github.com/saltstack/salt/issues/27494
  1. http://cewing.github.io/training.codefellows/assignments/day22/jinja2_walkthrough.html
  2. 在 Jinja2 中,将所有键设置为字典值的最简单方法是什么?
  3. https://github.com/saltstack/salt/issues/27494

回答by Арсений Пичугин

Without the jinja2.ext.doextension, you can do this:

如果没有jinja2.ext.do扩展,你可以这样做:

{% set x=my_dict.__setitem__("key", "value") %}

Disregard the xvariable and use the dictionary which is now updated.

忽略x变量并使用现在更新的字典。

UPD: Also, this works for len()(__len__()), str()(__str__()), repr()(__repr__()) and many similar things.

UPD:此外,这适用于len()( __len__())、str()( __str__())、repr()( __repr__()) 和许多类似的东西。

回答by Opster ES Ninja - Alper

Dictionaries do not have the append method. You can add a key-value pair like this though:

字典没有 append 方法。您可以添加这样的键值对:

{% do data['location']=node.location %} 

or

或者

{% do data.update({'location': node.location}) %}

回答by hemant_maverik

Key takeaways:

关键要点:

  1. dictionary does not support append().
  2. You can add the new item to the data dictionary by using {% do ... %}tag as shown here:

    {% do data.update({'location': node.location}) %}
    
  3. However, for the "do" tag to work properly you need to add the jinja2.ext.doextension to your jinja Environment.

  1. 字典不支持append()
  2. 您可以使用{% do ... %}标记将新项目添加到数据字典中,如下所示:

    {% do data.update({'location': node.location}) %}
    
  3. 但是,jinja2.ext.do要使“do”标签正常工作,您需要将扩展添加到您的 jinja 环境中。

回答by dsz

Without the doextension:

没有do扩展名:

{%- set _ = dict.update({c.name: c}) -%}

Works in base Jinja2 on Python 3, where the __setitem__solutions give me:

在 Python 3 上的基础 Jinja2 中工作,其中的__setitem__解决方案给了我:

access to attribute '__setitem__' of 'dict' object is unsafe