python - 搜索字典以查找键值
问题描述
我正在使用 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
解决方案
前言:此答案假定您的意图是搜索与您的搜索字符串完美匹配的内容。这意味着这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
)。
推荐阅读
- amazon-web-services - AWS 上的集群自动扩展不扩展
- bash - 如何从文件名中提取段?
- r - 无法弄清楚如何以不同的名称保存不同的 R 对象
- php - 更改公用文件夹名称和位置后未找到 Laravel 5 资源
- installation - Toad for Oracle 安装
- spring - Spring 5:如何加载静态资源(css、js、图片)
- angularjs - 表格行中的按钮 Angular 5
- api - 无需用户干预即可访问 Web API 的 AD FS 访问令牌
- javascript - 将引导程序迁移到 v4 - 弹出窗口不起作用
- angular - Angular 5 .- 组件属性没有更新???为什么?