user3498593
user3498593

Reputation: 95

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"

Upvotes: 0

Views: 370

Answers (1)

Kevin
Kevin

Reputation: 76194

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

Upvotes: 4

Related Questions