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
How to add a new entry into a dictionary object while using jinja2?
提问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:
我参考了以下和其他网络资源:
回答by Арсений Пичугин
Without the jinja2.ext.do
extension, you can do this:
如果没有jinja2.ext.do
扩展,你可以这样做:
{% set x=my_dict.__setitem__("key", "value") %}
Disregard the x
variable 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:
关键要点:
- dictionary does not support
append()
. You can add the new item to the data dictionary by using
{% do ... %}
tag as shown here:{% do data.update({'location': node.location}) %}
However, for the "do" tag to work properly you need to add the
jinja2.ext.do
extension to your jinja Environment.
- 字典不支持
append()
。 您可以使用
{% do ... %}
标记将新项目添加到数据字典中,如下所示:{% do data.update({'location': node.location}) %}
但是,
jinja2.ext.do
要使“do”标签正常工作,您需要将扩展添加到您的 jinja 环境中。
回答by dsz
Without the do
extension:
没有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