【问题标题】:Python searching dictionary for matching key用于匹配键的 Python 搜索字典
【发布时间】:2015-09-11 00:19:07
【问题描述】:

我正在尝试遍历 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

【问题讨论】:

    标签: python for-loop dictionary linear-search


    【解决方案1】:

    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'
    

    【讨论】:

    • 谢谢奈雪,我知道答案会很简单。感谢您的帮助。
    【解决方案2】:

    如果您不知道子网字典的字符串末尾总是'/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'
    

    【讨论】:

    • 感谢您的及时回复,不胜感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2019-12-12
    • 2016-07-26
    相关资源
    最近更新 更多