'Get simplified dictionary from a dict of dicts with Ansible

I have the following data structure:

site_subnets:
    control: { network: "100.99.97.0/24", mtu: "1500", vm_start_offset: 0, dhcp_from_ip: "30", dhcp_to_ip: "50" }
    storage: { network: "100.99.98.0/24", mtu: "9000", vm_start_offset: 0, dhcp_from_ip: "30", dhcp_to_ip: "50" }
    mission: { network: "100.99.99.0/24", mtu: "9000", vm_start_offset: 0, dhcp_from_ip: "30", dhcp_to_ip: "50" }
    site:    { network: "100.99.0.0/16", mtu: "1500", dhcp_from_ip: "30", dhcp_to_ip: "50" }
    local:   { network: "100.99.44.1/22", mtu: "1500", dhcp_from_ip: "30", dhcp_to_ip: "50" }

I want to end up with a new dictionary that looks like this:

site_subnets_simplified:
  control: "100.99.97.0/24"
  storage: "100.99.98.0/24"
  mission: "100.99.99.0/24"
  site: "100.99.0.0/16"
  local: "100.99.44.1/22"

Here's the playbook I've written:

 - set_fact:
     site_subnets_flat: "{{ site_subnets | combine | dict2items }}"

 - set_fact:
     site_subnets_simplified: "{{ site_subnets_simplified|default({}) + [ { item: item.network } ] }}"
   loop:
     - "{{ site_subnets_flat }}"

When I run it, I get an error that says "unhashable type: 'list'"

Is there a better or easier way to do this?



Solution 1:[1]

For example,

  site_subnets_keys: "{{ site_subnets.keys()|list }}"
  site_subnets_vals: "{{ site_subnets|json_query('*.network') }}"
  site_subnets_simplified: "{{ dict(site_subnets_keys|zip(site_subnets_vals)) }}"

gives

  site_subnets_simplified:
    control: 100.99.97.0/24
    local: 100.99.44.1/22
    mission: 100.99.99.0/24
    site: 100.99.0.0/16
    storage: 100.99.98.0/24

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 Vladimir Botka