我正在嘗試以嵌套字典的形式獲取輸出。我正在為網路模擬器的 python 自動化練習這個。我試過但無法實作。請有人幫助我。
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
輸出應采用以下格式。
{'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',
}
}
}
uj5u.com熱心網友回復:
如果您將輸入資料放在文本檔案(示例D:/test.txt)中,以下代碼將根據您的規范對其進行格式化:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429007.html
標籤:python-3.x 字典
