how to convert a for loop to a dictionary comprehension

21 views Asked by At

I'm trying to convert a dictionary-update method to dictionary comprehension.

for networkId in vlan_networks:
    vlan_network = dashboard.appliance.getNetworkApplianceVlans(networkId)
    vlan_by_networkid.update(
            {
                networkId : vlan_network[0]['subnet']
            }
        )

The end goal is to create a dictionary "vlan_by_networkid" with key:value pairs. ex: {'network1':'192.168.10.0/24', 'network2': '192.168.11.0/24', 'network3':'172.16.1.0/24'}

The current for loop works, and it creates the dictionary with pairs. I just want to use comprehension for run-time efficiency.

1

There are 1 answers

0
Andrej Kesely On

Try:

vlan_by_networkid = {
    networkId: dashboard.appliance.getNetworkApplianceVlans(networkId)[0]["subnet"]
    for networkId in vlan_networks
}