我有一個從 listip 中的 POST 回傳的 IP 串列。我想遍歷 IP 串列并將資料存盤在字典中,以便我可以在網頁上呈現它。但字典僅覆寫最后一個 IP 的值。我該如何解決這個問題?目前 listip 中有 3 個 IP,但 dict 僅存盤最后傳遞的 IP 資料。
def healthcheckresults(request):
if not listip:
return render(request, "home/homepage.html",)
for ip in range(len(listip)):
conn = manager.connect(
host= listip[ip],
port='22',
username='XXX',
password = 'XXX',
timeout=10
)
result = conn.get_ospf_neighbor_information()
hostnameresult = conn.get_software_information()
hostname = hostnameresult.xpath('//software-information/host-name/text()')
ospfneighboraddress = result.xpath('//ospf-neighbor/neighbor-address/text()')
ospfneighborinterface = result.xpath('//ospf-neighbor/interface-name/text()')
ospfneighborstate= result.xpath('//ospf-neighbor/ospf-neighbor-state/text()')
ospfneighborID = result.xpath('//ospf-neighbor/neighbor-id/text()')
##METHOD1
ospfdictkey = {"hostname":[],"ospfneighboraddress":[],"ospfneighborinterface":[],"ospfneighborstate":[],"ospfneighborID":[]}
ospfmetalist = [hostname,ospfneighboraddress,ospfneighborinterface,ospfneighborstate,ospfneighborID]
for key, value in zip(ospfdictkey, ospfmetalist):
ospfdictkey[key].append(value)
##METHOD2
ospfdict={"hostname":hostname,"ospfneighboraddress":ospfneighboraddress,"ospfneighborinterface":ospfneighborinterface, "ospfneighborstate":ospfneighborstate,"ospfneighborID":ospfneighborID }
context = {'LUnique': zip(ospfneighboraddress, ospfneighborinterface, ospfneighborstate,ospfneighborID)}
conn.close_session()
listip.clear()
return render(request, "healthcheck/healthcheckresults.html",{
"ospfneighboraddress":ospfneighboraddress,
"ospfneighborinterface":ospfneighborinterface,
"ospfneighborstate":ospfneighborstate,
"ospfneighborID":ospfneighborID,
"context":context,
"hostname":hostname,
"listip":listip,
"ospfdict":ospfdict,
"ospfdictkey":ospfdictkey,
})
當我檢查字典中的資料時,兩種提到的方法都回傳相同的資料。
{'主機名':['R3-ISP'],'ospfneighboraddress':['192.168.5.34','192.168.5.5','192.168.5.10'],'ospfneighborinterface':['ae10.0','ae2 .0', 'ae3.0'], 'ospfneighborstate': ['Full', 'Full', 'Full'], 'ospfneighborID': ['172.0.0.6', '172.0.0.2', '172.0.0.4 ']}
{'主機名':[['R3-ISP']],'ospfneighboraddress':[['192.168.5.34','192.168.5.5','192.168.5.10']],'ospfneighborinterface':[['ae10. 0', 'ae2.0', 'ae3.0']], 'ospfneighborstate': [['Full', 'Full', 'Full']], 'ospfneighborID': [['172.0.0.6', ' 172.0.0.2', '172.0.0.4']]} ['R3-ISP']
uj5u.com熱心網友回復:
在每種方法中,您都在覆寫 dict。請記住,代碼在每次迭代中重復
for ip in range(len(listip)):
這意味著,當您在每個方法的第一行中設定鍵和值時,您將覆寫該名稱的任何字典。
避免這種情況的一種方法是創建一個空串列,并在創建時將每個新 dict 附加到它。然后您可以回圈瀏覽串列以查看每個字典。
aList = []
for ip in range(len(listip)):
...
#Method1
...
aList.append(ospfdictkey )
#Method2
...
aList.append(ospfdict)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/485275.html
