I am trying to get the output in the form of nested dictionary. I am practicing this for python automation for Network simulator. I tried but not able to achieve. Kindly someone help me on this.
Interface IP-Address OK? Method Status Protocol
Vlan1 unassigned YES NVRAM up up
Vlan30 30.1.1.2 YES NVRAM up up
Vlan306 192.168.25.3 YES NVRAM up down
GigabitEthernet0/0 11.19.17.19 YES NVRAM up up
Te1/0/3 unassigned YES unset up up
Te1/0/21 unassigned YES unset up up
Te1/0/35 unassigned YES unset up up
output should be in below format.
{'interface': {
'vlan1': {
'name': 'vlan1',
'ip': 'unassigned',
'ok_status': 'YES',
'method': 'NVRAM',
'status': 'up',
'protocol': 'up',
},
'vlan30': {
'name': 'vlan30',
'ip': '30.1.1.2',
'ok_status': 'YES',
'method': 'NVRAM',
'status': 'up',
'protocol': 'up',
}
}
}
CodePudding user response:
If you place your input data in a text file (example D:/test.txt
), following code will format it according to your specification:
comma_sep = ""
with open("D:/test.txt") as f:
for line in f:
parts = [part for part in line.split(' ') if part != '']
comma_sep = ','.join(parts)
lines = [item for item in comma_sep.split('\n')]
output_dict = {"interface": {}}
for index, line in enumerate(lines):
if index == 0:
continue
# Compose each interface
interface = {}
for item_index, item in enumerate(line.split(',')):
if item_index == 0:
item = item.lower()
interface = {item: {}}
interface[item].update({'name': item})
main_key = item
elif item_index == 1:
interface[main_key].update({'ip': item})
elif item_index == 2:
interface[main_key].update({'ok_status': item})
elif item_index == 3:
interface[main_key].update({'method': item})
elif item_index == 4:
interface[main_key].update({'status': item})
elif item_index == 5:
interface[main_key].update({'protocol': item})
output_dict["interface"].update(interface)
print(output_dict)