Creating a list of dicts from a list - solution

Continuing the discussion from creating a list of dicts from a list:

I had this same requirement. This article keeps coming up in the google search results, but without a solution. Unfortunately the article is in the Archives and I can’t respond to it. I’m adding the solution I finally discovered for ‘future me’ or someone else that may stumble upon this.

Solution to @Tim1’s and my problem:

- name: "Create list of dict"
  vars:
    list1:
      - "foo"
      - "bar"
      - "baz"
  ansible.builtin.set_fact:
    list2: "{{ list1 | map('community.general.dict_kv', 'name') }}"
1 Like

For further reference, here’s some more documentation on the community.general.dict_kv filter: Dictionaries — Ansible Community Documentation

Its parent document, community.general Filter Guide — Ansible Community Documentation, has some more info on other filters in community.general, and then there’s also Using filters to manipulate data — Ansible Community Documentation. If someone happens to have a related problem for which the above solution doesn’t work exactly, these links might be helpful.

1 Like

FWIW, json_query gives the same result

_query: '[].{"name": @}'
list2: "{{ list1 | json_query(_query) }}"
1 Like