[英]Jinja2 map list to dictionary
Is it possible to convert list of primitives to list of dicts using Jinja2 using list/map comprehensions?是否可以使用 Jinja2 使用列表/映射理解将原语列表转换为字典列表?
Given this structure:鉴于这种结构:
list:
- some_val
- some_val_2
Apply map
on every element to obtain:在每个元素上应用
map
以获得:
list:
- statically_added: some_val
- statically_added: some_val_2
It is possible other way around: list_from_example|map(attribute="statically_added")|list
也可以采用其他方式:
list_from_example|map(attribute="statically_added")|list
I came up with the same question and found this solution:我提出了同样的问题并找到了这个解决方案:
- debug:
msg: "{{ mylist | json_query('[].{\"statically_added\": @}') }}"
vars:
mylist:
- some_val
- some_val_2
Output:输出:
ok: [localhost] => {
"msg": [
{
"statically_added": "some_val"
},
{
"statically_added": "some_val_2"
}
]
}
I ended up writing my own, tiny filter.我最终编写了自己的微型过滤器。 I'm using Ansible, but I hope it's possible to adapt it for other environments as well.
我正在使用 Ansible,但我希望它也可以适用于其他环境。
For Ansible place this into file filter_plugins/singleton_dict.py
:对于 Ansible,将其放入文件
filter_plugins/singleton_dict.py
:
class FilterModule(object):
def filters(self):
return {
'singleton_dict':
lambda element, key='singleton': {
key: element
}
}
Then [1, 2]|singleton_dict(key='name')
produces [{'name': 1}, {'name': 2}]
.然后
[1, 2]|singleton_dict(key='name')
产生[{'name': 1}, {'name': 2}]
。 When no key=
is specified, it defaults to 'singleton'
.如果未指定
key=
,则默认为'singleton'
。
It's actually pretty simple.其实很简单。 At least, this works in Ansible:
至少,这在 Ansible 中有效:
vars:
my_list:
- some_val
- some_val_2
dict_keys:
- key_1
- key_2
tasks:
- debug:
msg: "{{ dict(dict_keys | zip(my_list)) }}"
Output:输出:
TASK [debug] *******************************
ok: [localhost] => {
"msg": {
"key_1": "some_val",
"key_2": "some_val_2"
}
} }
Note that you have to provide a list of keys, and they need to be distinct (the nature of dictionary implies that keys can't be the same).请注意,您必须提供一个键列表,并且它们需要是不同的(字典的性质意味着键不能相同)。
UPDATE.更新。 Just realised that the title was a bit misleading, and I answered the title, not the actual question.
刚意识到标题有点误导,我回答的是标题,而不是实际问题。 However, I'm going to leave it as it is, because I believe many people will google for converting a list into a dictionary and find this post.
但是,我将保持原样,因为我相信很多人会在谷歌上将列表转换为字典并找到这篇文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.