1

I will post the error which I get in my python code. I get keyerror in my destination ip address when I read my log file

  if "dstport" in p:

                if p["dstport"] in counts:
                    counts[str(p["dstport"])] += 1
                else:
                    counts[str(p["dstport"])] = 1

                if p["dstip"] in ip_counts:
                    ip_counts[str(p["dstip"])] += 1
                else:
                    ip_counts[str(p["dstip"])] = 1
                asc_order.append(p["dstport"])

                ip_port[p["dstip"]] = int(p["dstport"])
            else:
                print "ini"
                if p["dstip"] in ip_counts:
                    ip_counts[str(p["dstip"])] += 1
                else:
                    ip_counts[str(p["dstip"])] = 1                    
    print ip_counts
    sorted_x = sorted(ip_port.items(), key=operator.itemgetter(1))
    ip_list = [ip for ip, port in sorted_x]
    ip_short_long = [ip2long(ips) for ips in ip_list]
    ip_short_long.sort()
    ip_sort = [long2ip(ip) for ip in ip_short_long]    
    for ip in ip_sort:
        print ip 
if __name__ == "__main__": main()

My error is

     if p["dstip"] in ip_counts:
    KeyError: 'dstip'   
Angeline
  • 109
  • 10

1 Answers1

1

Use p.get("dstip") while checking the condition.
So it will not throw an exception if there is no such key in dictionary.

Why using get intead of dict["key"] ?

bhansa
  • 7,282
  • 3
  • 30
  • 55