I am trying to iterate over a list of IP addresses and check whether each IP address exists as a dictionary key. My for-loop is returning the desired result for IP addresses that are found in the dictionary, however for IP addresses that are not found, the loop returns the IP address multiple times. Any ideas on a better way to do this.
subnet_dict = {'10.6.150.2/32': 'site-A', '10.2.150.2/32': 'site-B', '10.1.2.2/32': 'site-C'}
datafile = [['27/08/2015 18:23', '10/09/2015 12:20', '10.1.2.2', '15356903000'], ['3/09/2015 8:54', '3/09/2015 20:03', '10.1.2.3', '618609571'],
['27/08/2015 22:23', '10/09/2015 10:25', '10.1.2.4', '6067520'], ['27/08/2015 20:14', '10/09/2015 1:35', '10.99.88.6', '4044954']]
for row in datafile:
dstip = row[2]
for key, value in subnet_dict.iteritems():
if dstip in key:
print dstip, value + ' was FOUND in the dictionary'
else:
print dstip + ' was not found'
Output:
10.1.2.2 was not found
10.1.2.2 was not found
10.1.2.2 site-C was FOUND in the dictionary
10.1.2.3 was not found
10.1.2.3 was not found
10.1.2.3 was not found
10.1.2.4 was not found
10.1.2.4 was not found
10.1.2.4 was not found
10.99.88.6 was not found
10.99.88.6 was not found
10.99.88.6 was not found
Desired Output:
10.1.2.2 site-C was FOUND in the dictionary
10.1.2.3 was not found
10.1.2.4 was not found
10.99.88.6 was not found
Python has a very simple solution for you (notice the change in indentation):
for row in datafile:
dstip = row[2]
for key, value in subnet_dict.iteritems():
if dstip in key:
print dstip, value + ' was FOUND in the dictionary'
break
else:
print dstip + ' was not found'