I have a dictionary as follows:
dictionary = {'happen1':['happen later'], 'happen2':['happen'], 'happen3':['happen later',' happen tomorrow'], 'happen4':['happen now'], 'happen5':['happen again','never happen']}
I have a string as follows.
my_string = 'happen this news on TV'
but I would like to do is to find the exact match of the first word of the string with the values in the dictionary and then replace it with the corresponding key.
def replacer():
result = []
for key,val in dictionary.items():
if any(my_string.split(' ', 1)[0] in s for s in val):
done= my_string.split(' ', 1)[0].replace(val, key.split(' ', 1)[0]) + ' to me' + ' ' + ' '.join(my_string.split()[1:])
result.append(done)
return result
the current output:
['happen to me this news on TV', 'happen2 to me this news on TV', 'happen to me this news on TV', 'happen to me this news on TV', 'happen to me this news on TV']
the problem is when I run the function, it returns all possible matches, however I only want it to return the match for the value of the key 'happen2'. so the desired output would be:
['happen2 to me this news on TV']
Try this:
def replacer():
my_words = my_string.split(" ")
result = []
for key, value in dictionary.items():
for item in value:
if item == my_words[0]:
result.append(key + " to me " + " ".join(my_words[1:]))
return result