简体   繁体   English

Python词典列表仅查看最后一个元素

[英]Python List of Dictionaries Only See Last Element

Struggling to figure out why this doesn't work. 努力弄清楚为什么它不起作用。 It should. 这应该。 But when I create a list of dictionaries and then look through that list, I only ever see the final entry from the list: 但是,当我创建字典列表然后浏览该列表时,我只会看到该列表中的最后一个条目:

alerts = []
alertDict = {}
af=open("C:\snort.txt")

for line in af:
    m = re.match(r'([0-9/]+)-([0-9:.]+)\s+.*?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})\s+->\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})', line)
    if m:
        attacktime = m.group(2)
        srcip = m.group(3)
        srcprt = m.group(4)
        dstip = m.group(5)
        dstprt = m.group(6)
        alertDict['Time'] = attacktime
        alertDict['Source IP'] = srcip
        alertDict['Destination IP'] = dstip
    alerts.append(alertDict)

for alert in alerts:
    if alert["Time"] == "13:13:42.443062":
        print "Found Time"

You create exactly one dict at the beginning of the script, and then append that one dict to the list multiple times. 您在脚本的开头精确地创建了一个字典,然后将该一个字典多次追加到列表中。

Try creating multiple individual dicts, by moving the initialization to the inside of the loop. 通过将初始化移到循环内部,尝试创建多个单独的字典。

alerts = []
af=open("C:\snort.txt")

for line in af:
    alertDict = {}
    #rest of loop goes here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM