Skip to main content
 首页 » 编程设计

键上的 Python dict of dict 正则表达式

2024年10月25日34jirigala

我仍在努力学习 Python 中的字典。是否可以使用正则表达式或 startswith 函数在字典中引用键?

我有以下格式的字典,我正在尝试对“AreaOfInterest1”、“AreaOfInterest2”、“AreaOfInterest3”等进行一般搜索。我将其设为通用,然后引用关联的列表值[0 ] 执行操作。

我的字典看起来像...

FeatureDict = { 
    "MATCHcode96":{ 
    'ID':'MATCHcode96', 
    'AreaOfInterest1':['String 1','%',0], 
    'AreaOfInterest2':['String 2','Avg',[]], 
    'AreaOfInterest3':['String 3','Avg',[]], 
    }, 
    "MATCHcode9F":{ 
    'ID':'MATCHcode9F', 
    'AreaOfInterest1':['String 1','%',0], 
    'AreaOfInterest2':['String 2','Avg',[]], 
    }, 
} 

我正在寻找的功能是使用 startswith(如下所示)或尝试正则表达式..

for dict in FeatureDict: 
    if FeatureDict[dict]['ID'] in mypkt.Text:                
        if FeatureDict[dict][startswith.('AreaOfInterest')][0] in mypkt.Text: 
            print 'found'    

谢谢。

请您参考如下方法:

不,dict 不支持基于键的功能或键的部分匹配的查找。 dict 确实支持迭代,因此您可以以 O(n) 的成本进行自己的查找。 (dict 查找通常是 O(1))。

for outer_key, outer_val in FeatureDict.items(): 
    if outer_val['ID'] in mypkt.Text: 
        for inner_key, inner_val in outer_val: 
            if inner_key.startswith('AreaOfInterest') and inner_val in mypkt.Text: 
                print found 
                break