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?
-
Use a loop, iterate over the the key and use your own condition – azro Jul 25 '22 at 20:43
-
take a look at this question https://stackoverflow.com/questions/18715688/find-common-substring-between-two-strings. I think its in the spirit of what you are asking. you can set a minimum substring match to your key and the dictionary and return all keys that fit. This will be quite slow though – Sam Jul 25 '22 at 20:51
-
1Dictionaries rely on an object hash, and one of the properties of a good hash is that even the smallest change to the object results in a completely different hash. A dictionary may be the wrong data structure for your use case. – Mark Ransom Jul 25 '22 at 20:51
3 Answers
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...

- 11,962
- 4
- 34
- 48
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.

- 20,545
- 20
- 91
- 102