Convert "list of dict" into "dict of dict"

Hi all,

I tried to convert state_attr('sensor.network_scanner', 'devices') into another format.
It is exactly {d['mac']: {'ip': d['ip'], 'name': d['name']} for d in device_list} in Python.

For example, converting from

[
  {
    "ip": "192.168.0.1",
    "mac": "AA:AA:AA:AA:AA:AA",
    "name": "Device A",
  },
  {
    "ip": "192.168.0.2",
    "mac": "BB:BB:BB:BB:BB:BB",
    "name": "Device B",
  },
]

to

{
  "AA:AA:AA:AA:AA:AA": {
    "ip": "192.168.0.1",
    "name": "Device A",
  },
  "BB:BB:BB:BB:BB:BB": {
    "ip": "192.168.0.2",
    "name": "Device B",
  },
}

The closest script I could get is {{ device_list | groupby('mac') }} but it is still not key by mac address.

[
  [
    "AA:AA:AA:AA:AA:AA",
    [
      {
        "ip": "192.168.0.1",
        "mac": "AA:AA:AA:AA:AA:AA",
        "name": "Device A",
      }
    ]
  ],
  [
    "BB:BB:BB:BB:BB:BB",
    [
      {
        "ip": "192.168.0.2",
        "mac": "BB:BB:BB:BB:BB:BB",
        "name": "Device B",
      }
    ]
  ],
]

Another trial is selecting each field first but I do not know how to merge them into dict.

{% set mac = device_list | map(attribute='mac') | list %} <--- list of MAC address
{% set ip = device_list | map(attribute='ip') | list %} <--- list of IP address
{{ ???? }}

Any idea will be appreciated. Thanks!

Here you go:

{% set data = 
      [
        {
          "ip": "192.168.0.1",
          "mac": "AA:AA:AA:AA:AA:AA",
          "name": "Device A",
        },
        {
          "ip": "192.168.0.2",
          "mac": "BB:BB:BB:BB:BB:BB",
          "name": "Device B",
        },
      ]
%}
{% set ns = namespace(new_data = {}) %}
{% for i in data %}
  {% set add = { i.mac: { 'ip': i.ip, 'name': i.name }} %}
  {% set ns.new_data = dict(ns.new_data, **add) %}
{% endfor %}
{{ ns.new_data }}

output:

{
  "AA:AA:AA:AA:AA:AA": {
    "ip": "192.168.0.1",
    "name": "Device A"
  },
  "BB:BB:BB:BB:BB:BB": {
    "ip": "192.168.0.2",
    "name": "Device B"
  }
}

Not sure why you’d need this though, you can get any data out of the other format as well.

Thanks a lot!
I wanted to perform multiple searches based on MAC address so I thought it will be easier to modify the data structure with keys. After searching around, looks like selectattr can do the same as well.