Home > Net >  Is there a way to match to a key partially?
Is there a way to match to a key partially?

Time:07-26

I am working with a set of key words and a dictionary in python and am looking to match the keywords with the keys in the dictionary but just partially. For example if I have a key word like wide-plank floors I would like to match it to some key 'floor'. Is there a way I can just check for partial?

CodePudding user response:

Q: Is there a way to match to a key partially?

Short answer: No.

Reason:

How Dictionaries Work in Python

keys are “hashed.” Python dictionaries are implemented as a hash table behind the scenes. The dictionary uses each key’s hash function to change some of the key’s information into an integer known as a hash value.

So the only way to do a "partial search" (e.g. check the key against a "wildcard pattern") is to loop through each of the keys until you find a match.

Of course, once you find a matching key (by inspecting each key in turn), then you can use the dictionary to look up the corresponding value.

But you can't use the dictionary itself for a "wildcard lookup".

'Hope that helps...

CodePudding user response:

You can create a filtered dictionary:

dx = {k: v for k, v in original if "floor" in k}

Then you can assume the keys in dx all share the property of containing 'floor', and just work with the values. If you need to do something more complex, replace if "floor" in k with if f(k), where f() is some function you write to decide if a key k should be included in the final set you're working with.

CodePudding user response:

Something like this would work:

for keyword in keyword_dict:
    if search_term in keyword:
        print(keyword_dict[keyword])
  • Related