Python List of Dictionaries Only See Last Element

纵然是瞬间 提交于 2019-12-25 07:42:16

问题


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"

回答1:


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


来源:https://stackoverflow.com/questions/38444344/python-list-of-dictionaries-only-see-last-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!