Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

752
Views
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

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!