Python 在字典中搜索匹配键

Python searching dictionary for matching key

我正在尝试遍历 IP 地址列表并检查每个 IP 地址是否作为字典键存在。对于在字典中找到的 IP 地址,我的 for 循环返回所需的结果,但是对于未找到的 IP 地址,循环 returns 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

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'

如果您不知道 subnet_dict 的字符串末尾总是“/32”,您可以这样做:

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'