Home > Software design >  python: return the exact match from list of values in a dictionary
python: return the exact match from list of values in a dictionary

Time:09-23

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']

CodePudding user response:

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

CodePudding user response:

How about doing it this way:-

def replacer(ms, md):
    tokens = ms.split()
    firstWord = tokens[0]
    for k, v in md.items():
        if firstWord in v:
            return k   ' '   ' '.join(tokens[1:])

myString = 'happen this news on TV'
myDict = {'happen1':['happen later'], 'happen2':['happen'], 'happen3':['happen later',' happen tomorrow'], 'happen4':['happen now'], 'happen5':['happen again','never happen']}

print(replacer(myString, myDict))

CodePudding user response:

def replacer(dictionary, string):
    replaced = []
    for key, val in dictionary.items():
        for v in val:
            if string.startswith(v):
                replaced.append(string.replace(v, key))
    return replaced

Output:

>>> dictionary = {'happen1':['happen later'], 'happen2':['happen'], 'happen3':['happen later',' happen tomorrow'], 'happen4':['happen now'], 'happen5':['happen again','never happen']}
>>> my_string = 'happen this news on TV'
>>> replacer(dictionary, my_string)
['happen2 this news on TV']
  • Related