Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 map list to dictionary

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

like image 592
lakier Avatar asked Feb 27 '18 11:02

lakier


1 Answers

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"
        }
    ]
}

like image 59
Matthias Lohr Avatar answered Oct 18 '22 23:10

Matthias Lohr