MikG
MikG

Reputation: 1019

Python dict of dict Regex on keys

I'm still getting to grips with dictionaries in Python. Is it possible to reference the Key in a dict of dicts by using either a regex or a startswith function?

I have a dict of dicts in the following format and I am trying to do a general search for 'AreaOfInterest1','AreaOfInterest2','AreaOfInterest3' etc. I make it general as I then refer the associated list value[0] to perform actions.

My dict of dicts would look something like...

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',[]],
    },
}

The kind of functionality I am looking for is either to use startswith (like below) or otherwise try regex..

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

Thanks.

Upvotes: 2

Views: 249

Answers (2)

Celeo
Celeo

Reputation: 5682

Just keep looping:

ids = ['MATCHcode9F']
area_ids = ['String 1']
for key in data:
    if data[key]['ID'] in ids:
        for inner_key in data[key]:
            if inner_key.startswith('AreaOfInterest') and data[key][inner_key][0] in area_ids:
                print('found')

So your code would look like

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

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168626

No, dict does not support lookups based on functions of the key or partial matches of the key. dict does support iteration, so you can do your own lookup, at a O(n) cost. (dict lookup is ordinarily 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

Upvotes: 1

Related Questions