I am trying to get all indexes of the keys in the string and store them in a dict, so that every index has a list of keys mapping to it.
Example:
string = "loloo and foofoo at the foo bar"
keys = "foo", "loo", "bar", "lo"
i expect something like
{
0: [lo]
2: [loo, lo]
10: [foo]
13: [foo]
24: [foo]
28: [bar]
}
My current answer loos the following:
def get_index_for_string(string, keys):
"""
Get all indexes of the keys in the string and store them in a dict, so that
every index has a list of keys mapping to it.
"""
key_in_string = dict((key, [m.start() for m in re.finditer(key, string)])
for key in keys if key in string)
index_of_keys = {}
for key, values in key_in_string.items():
for value in values:
if not value in index_of_keys:
index_of_keys[value] = []
index_of_keys[value].append(key)
return index_of_keys
Any suggestions on how to make this better?