I have a list of dictionaries where I need to remove anything from the interfaces keys that is Po...... and I need to remove the Vl from the Vlan interfaces, just keeping the Vlan number. I need to change the following list of dictionaries:
vrfs = [
{'default_rd': '<not set>',
'interfaces': ['Gi0/0'],
'name': 'Mgmt-vrf',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:510',
'interfaces': ['Po31.510', 'Po32.510', 'Vl503', 'Vl510', 'Vl515'],
'name': 'VLAN1',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:993',
'interfaces': ['Po31.993', 'Po32.993', 'Vl993'],
'name': 'VLAN2',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:855',
'interfaces': ['Po31.855', 'Po32.855', 'Vl855'],
'name': 'VLAN3',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:266',
'interfaces': ['Po31.266', 'Po32.266', 'Vl266'],
'name': 'VLAN4',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:248',
'interfaces': ['Po31.248', 'Po32.248', 'Vl248'],
'name': 'VLAN5',
'protocols': 'ipv4,ipv6'}
]
To look like this:
vrfs = [
{'default_rd': '<not set>',
'interfaces': ['Gi0/0'],
'name': 'Mgmt-vrf',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:510',
'interfaces': ['503', '510', '515'],
'name': 'VLAN1',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:993',
'interfaces': ['993'],
'name': 'VLAN2',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:855',
'interfaces': ['855'],
'name': 'VLAN3',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:266',
'interfaces': ['266'],
'name': 'VLAN4',
'protocols': 'ipv4,ipv6'},
{'default_rd': '12345:248',
'interfaces': ['248'],
'name': 'VLAN5',
'protocols': 'ipv4,ipv6'}
]
What’s the best way to accomplish this?
>Solution :
Try:
for d in vrfs:
d["interfaces"] = [v.replace("Vl", "") for v in d["interfaces"] if not v.startswith("Po")]
print(vrfs)
Prints:
[
{
"default_rd": "<not set>",
"interfaces": ["Gi0/0"],
"name": "Mgmt-vrf",
"protocols": "ipv4,ipv6",
},
{
"default_rd": "12345:510",
"interfaces": ["503", "510", "515"],
"name": "VLAN1",
"protocols": "ipv4,ipv6",
},
{
"default_rd": "12345:993",
"interfaces": ["993"],
"name": "VLAN2",
"protocols": "ipv4,ipv6",
},
{
"default_rd": "12345:855",
"interfaces": ["855"],
"name": "VLAN3",
"protocols": "ipv4,ipv6",
},
{
"default_rd": "12345:266",
"interfaces": ["266"],
"name": "VLAN4",
"protocols": "ipv4,ipv6",
},
{
"default_rd": "12345:248",
"interfaces": ["248"],
"name": "VLAN5",
"protocols": "ipv4,ipv6",
},
]