首页 > 解决方案 > 搜索字典以查找键值

问题描述

我正在使用 python 2.7,并且我有以下字典

my_dict = {}

my_dict["GI2/1/1"] = [
'switchport port-security maximum 10', 
'switchport port-security maximum 3 vlan access', 
'switchport port-security maximum 1 vlan voice', 
'switchport port-security aging time 25', 
'switchport port-security aging type inactivity', 
'switchport port-security'
]

my_dict["GI2/1/2"] = [
'switchport port-security maximum 5', 
'switchport port-security maximum 5 vlan access', 
'switchport port-security maximum 3 vlan voice', 
'switchport port-security aging time 20', 
'switchport port-security aging type inactivity', 
'switchport port-security'
]


my_dict["GI2/1/3"] = [
'switchport port-security maximum 10', 
'switchport port-security maximum 3 vlan access', 
'switchport port-security maximum 1 vlan voice', 
'switchport port-security aging time 25', 
'switchport port-security aging type inactivity', 
'switchport port-security'
]

我希望能够搜索这些值,让我们说这样switchport port-security maximum 10的话,并让它能够给我所有拥有它的键,然后能够获得该键的完整值列表。

我有以下代码,但没有产生任何东西

x = "port-security maximum 10"

for name, val in my_dict.iteritems():
    if x in val:
        print name

标签: pythonpython-2.7

解决方案


前言:此答案假定您的意图是搜索与您的搜索字符串完美匹配的内容。这意味着这x = 'port-security maximum 10'是原始问题中的错字。如果要搜索部分字符串,则必须像其他答案建议的那样进行线性搜索(除非您预先构建了一个 trie,但我不想这样做)。

您的直接问题是它x不像您的值中的所有字符串那样以单词开头switchport,所以当然找不到。你的循环实际上完全没问题。

如果这是您需要经常执行的操作,请反转字典。字典的重点是允许快速键查找。跨多个值进行线性搜索似乎对您的数据结构的使用非常糟糕:

reversed = {}
for name, val in my_dict.iteritems():
    for key in val:
        if key not in reversed:
            reversed[key] = set()
        reversed[key].add(name)

现在你可以这样做:

reversed["switchport port-security maximum 10"]

要得到

set(['GI2/1/1', 'GI2/1/3'])

我使用了一个集合而不是一个列表来允许一个值my_dict包含重复。如果这种情况永远不会发生,您最好使用列表(.append而不是.add)。


推荐阅读