用于匹配键的 Python 搜索字典

Posted

技术标签:

【中文标题】用于匹配键的 Python 搜索字典【英文标题】:Python searching dictionary for matching key 【发布时间】: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

【问题讨论】:

【参考方案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'

【讨论】:

感谢您的及时回复,不胜感激。

以上是关于用于匹配键的 Python 搜索字典的主要内容,如果未能解决你的问题,请参考以下文章

用于匹配字典中单词的 JavaScript 算法

如何在嵌套的 Python 字典中搜索匹配的数据框值,然后更新数据框?

用于匹配和计数的字符串和 int 的容器?

字典键上的正则表达式匹配

Python Pandas Regex:在列中搜索带有通配符的字符串并返回匹配项[重复]

使用dictionary_1的键在dictionary_2的值中搜索匹配项[重复]