Best way to iterate list with substrings and replace an upper string

77 views Asked by At

I want to improve my code's performance and running time, looking for write my loops better.

For example, I have a dictionary that contains words as keys, and their translation in Spanish as values.

{
    'Hello' : 'Hola',
    'Goodbye' : 'Adios',
    'Cheese' : 'Queso'
}

I also have a given English sentence, and I want to iterate over any word in my dict and replace it with the Spanish translation. For this scenario I consider that up to one word could be exist in the given sentence.

I wrote a basic code that do that, but I am not sure that it is best practice:

words_list = {
        'Hello' : 'Hola',
        'Goodbye' : 'Adios',
        'Cheese' : 'Queso'
    }
sentence = "Hello, I want to talk Spanish"

for english_word in words_list.keys():
    if english_word in sentence:
        sentence = sentence.replace(english_word, words_list[english_word])
        break

print sentence

How can I write it better?

Thanks!

0

There are 0 answers