Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace strings in list from dictionary

Tags:

python

I'm having some issues with my code:

word_list = { "hello" : "1", "bye" : "2"}

sentence= ['hello you, hows things', 'hello, good thanks']

for key, value in word_list.iteritems():
   for i in sentence:
       i = i.replace(key, value)
print i

Expected output = '1 you, how's things', '1, good thanks'

It currently does not replace any occurrences of hello. I'm wondering if my sentence loop is correct or not? Printing i after this prints out exactly what is in sentence.

like image 696
user47467 Avatar asked Sep 05 '25 07:09

user47467


1 Answers

I guess the word_list(try to rename the variable to word_dict, I think that is more appropriate) has lots of items,

for index, data in enumerate(sentence):
    for key, value in word_list.iteritems():
        if key in data:
            sentence[index]=data.replace(key, word_list[key])

working example from ipython

In [1]: word_list = { "hello" : "1", "bye" : "2"}

In [2]: sentence = ['hello you, hows things', 'hello, good thanks']

In [3]: for index, data in enumerate(sentence):
   ...:         for key, value in word_list.iteritems():
   ...:                 if key in data:
   ...:                         sentence[index]=data.replace(key, word_list[key])
   ...:             

In [4]: sentence
Out[4]: ['1 you, hows things', '1, good thanks']
like image 105
Jithin Avatar answered Sep 07 '25 20:09

Jithin