'How can I convert a list of dictionaries into a dictionary of lists in ansible?

It's kind of a challenge for me to use correct ansible filters.
Can someone help me with how I can convert a list of dictionaries?

This is my input data:

"_list_of_dict":
[
        {
            "groupid": "11",
            "hostname": "host1.local",
            "timeout": "5000",
            "status": "ONLINE",
        },
        {
            "groupid": "12",
            "hostname": "host1.local",
            "timeout": "5000",
            "status": "ONLINE",
        },
        {
            "groupid": "12",
            "hostname": "host2.local",
            "timeout": "5000",
            "status": "ONLINE",
        }
    ]

And this what I would like to get:

"_dict_of_list": {
        "12": [
            {
                "hostname": "host2.local",
                "timeout": "5000",
                "status": "ONLINE",
            },
            {
                "host": "host1.local",
                "timeout": "5000",
                "status": "ONLINE",
            }
        ],
        "11": [
            {
                "host": "host1.local",
                "timeout": "5000",
                "status": "ONLINE",
            }
        ],

It might be that the list contains different numbers of groupid and each group could have different numbers of hosts and I have to combine them by groupid.



Solution 1:[1]

I found a solution myself. That works for me. Thanks, to everyone who tried to help I really appreciate it.

    _dict_of_list: >-
          {{ _dict_of_list | default({})
            | combine({item.groupid: []
            + [{
                'hostname': item.hostname,
                'timeout': item. timeout,
                'status': item. status
              }]
            + _dict_of_list[item.groupid] | default([]) })
          }}
  with_items: "{{ _list_of_dict }}"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Artemii Emelianov