繁体   English   中英

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

[英]Python List of Dictionaries Only See Last Element

努力弄清楚为什么它不起作用。 这应该。 但是,当我创建字典列表然后浏览该列表时,我只会看到该列表中的最后一个条目:

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"

您在脚本的开头精确地创建了一个字典,然后将该一个字典多次追加到列表中。

通过将初始化移到循环内部,尝试创建多个单独的字典。

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