I have a Python dictionary, a sample structure of which is as below (excerpt):
items = {
"Google": "Mountain View",
"Johnson & Johnson": "New Brunswick",
"Apple": "Cupertino",
}
Now what I have is a string, namely str1. What I want to do is look if any of the keys from dictionary items is present in string str1, for example if I have a string like Where is Google based out of?. Initially I wrote this pseudo code:
for str_word in str1.split():
if str_word in items:
print("Key found. Value is = ".format(items[str_word]))
Now this is good as dictionary keys are indexed/hashed. So the in operator runtime is constant but as you can notice this works fine for words like Google or Apple but this will not work for Johnson & Johnson (if my string is Where is Jonhnson & Johnson based out of?).
The other way I can think of is to first extract all the keys from the dictionary and then iterate one-by-one over each key and see if it is present in the str1 (reverse of first approach). This will increase the runtime as my dictionary is huge with hundreds or thousands of keys.
I want to know if there is a way I can modify my first approach to count for being able to match a sub-string with keys of a dictionary that could contain multiple words like Johnson & Johnson?