Is it possible to convert list of primitives to list of dicts using Jinja2 using list/map comprehensions?
Given this structure:
list:
- some_val
- some_val_2
Apply map on every element to obtain:
list:
- statically_added: some_val
- statically_added: some_val_2
It is possible other way around: 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"
}
]
}
It's actually pretty simple. At least, this works in 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.