Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading