data conversion question

Hello,
I’ve got a list variable that looks like this
list:

  • name: n1
    group: g1
  • name: n2
    group: g1
  • name: c1
    group: g2
    etc…

in my config file, this should become:
g1: n1,n2
g2: c1

etc…

how can this be done?

* Given the list

  _list:
    - {group: g1, name: n1}
    - {group: g1, name: n2}
    - {group: g2, name: c1}

* Use *groupby*

  _arr: "{{ _list|groupby('group') }}"

  gives

  _arr:
    - - g1
      - - {group: g1, name: n1}
        - {group: g1, name: n2}
    - - g2
      - - {group: g2, name: c1}

* Create lists of keys and values

  _keys: "{{ _arr|map('first')|list }}"
  _vals: "{{ _arr|map('last')|map('map', attribute='name')|list }}"

  gives

  _keys:
    [g1, g2]
  _vals:
    - [n1, n2]
    - [c1]

* Create the dictionary

  _dict: "{{ dict(_keys|zip(_vals)) }}"

  gives

  _dict:
    g1: [n1, n2]
    g2: [c1]

Thank you, Vladimir.
It works. Is there any trick to make this with one-liner?

Sure. The one-liner below does the job as well. You're welcome

  _dict: "{{ dict(_list|groupby('group')|map('first')|list|
              zip(_list|groupby('group')|map('last')|
                                         map('map',
                                         attribute='name')|list))
                                         }}"

Hello,
I’ve got a list variable that looks like this
list:

  • name: n1
    group: g1
  • name: n2
    group: g1
  • name: c1
    group: g2
    etc…

in my config file, this should become:
g1: n1,n2
g2: c1

I’m assuming a config file here, so can you render it? The example format he docs on the groupby module comes in handy. https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.groupby

{% for group, values in (list | groupby(‘group’) %}

{{ group }}:{% for item in value %}{{ item }},{% endfor %}

The template can be fixed

  {% for group, values in _list|groupby('group') %}
  {{ group }}: {{ values|map(attribute='name')|join(',') }}
  {% endfor %}

to get the expected result

  g1: n1,n2
  g2: c1