无法将新列表数据附加到 for 循环中的字典

Cannot Append new list data to a dict in a for loop

我有一个从 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,
})

当我检查字典中的数据时,上述两种方法都返回相同的数据。

{'hostname': ['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']}

{'hostname': [['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']

在每种方法中,您都在覆盖字典。请记住,代码在

的每次迭代中重复
for ip in range(len(listip)):

这意味着当您在每个方法的第一行设置键和值时,您将覆盖之前已经存在的同名字典。

避免这种情况的一种方法是创建一个空列表,并在创建时将每个新字典附加到它。然后您可以循环浏览列表以查看每个字典。

aList = []
for ip in range(len(listip)):
...
#Method1
...
aList.append(ospfdictkey )
#Method2
...
aList.append(ospfdict)