Python搜索字典匹配键

时间:2015-09-11 00:19:08

标签: python for-loop dictionary linear-search

我正在尝试迭代IP地址列表并检查每个IP地址是否作为字典键存在。我的for循环返回字典中找到的IP地址的所需结果,但是对于未找到的IP地址,循环多次返回IP地址。有关更好的方法的任何想法。

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'

输出:

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

期望的输出:

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

2 个答案:

答案 0 :(得分:0)

Python为您提供了一个非常简单的解决方案(注意缩进的变化):

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'

答案 1 :(得分:0)

如果你不知道它总会成为' / 32'在subnet_dict的字符串末尾你可以这样做:

for row in datafile:
    dstip = row[2]
    if dstip in [str.split('/')[0] for str in subnet_dict.keys()]:
        for k in subnet_dict:
            if k.split('/')[0] == dstip:
                print dstip + ' ' + subnet_dict[k] + ' was FOUND in the dictionary'
    else:
        print dstip + ' was not found'

如果你这样做,那就足够了:

for row in datafile:
    dstip = row[2]
    if dstip + '/32' in subnet_dict:
        print dstip + ' ' + subnet_dict[dstip + '/32'] + ' was FOUND in the dictionary'
    else:
        print dstip + ' was not found'
相关问题