Dictionary Comprehension within a List Comprehension

I have a list of dictionaries, that I’m modifying values in. I have a for loop that works as expected.

show_mac = [{'mac': '0000.0000.0000', 'port': 'GigabitEthernet1/1', 'type': 'dynamic', 'vlan': '1'},
            {'mac': '0000.0000.0000', 'port': 'TenGigabitEthernet2/1', 'type': 'dynamic', 'vlan': '1'},
            {'mac': '0000.0000.0000', 'port': 'Port-channel1', 'type': 'dynamic', 'vlan': '1'}]

for d in show_mac:
    for k, v in d.items():
        d[k] = (
            v.replace('TenGigabitEthernet', 'Te')
            .replace('GigabitEthernet', 'Gi')
            .replace('Port-channel', 'Po')
        )

pprint(show_mac)

Which produces this:

[{'mac': '0000.0000.0000', 'port': 'Gi1/1', 'type': 'dynamic', 'vlan': '1'},
 {'mac': '0000.0000.0000', 'port': 'Te2/1', 'type': 'dynamic', 'vlan': '1'},
 {'mac': '0000.0000.0000', 'port': 'Po1', 'type': 'dynamic', 'vlan': '1'}]

I’m learning how to write comprehensions, and I’m trying to figure out how can I use list and dictionary comprehension on the above for loop to achieve the same results?

>Solution :

It is hard to read/understand, but this works:

show_mac = [{key:value.replace('TenGigabitEthernet', 'Te').replace('GigabitEthernet', 'Gi').replace('Port-channel', 'Po') for (key, value) in line.items()}) for line in show_mac]
print(show_mac)

Leave a Reply