user47467
user47467

Reputation: 1093

Replace strings in list from dictionary

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.

Upvotes: 4

Views: 8897

Answers (5)

Vorsprung
Vorsprung

Reputation: 34307

The replacement occurs on a variable inside the loop So nothing is changed in the sentence list To fix this make a new list with the changed items in it

word_list = { "hello" : "1"}

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

for key, value in word_list.items():
   for i in sentence:
       i = i.replace(key, value)
       newlist.append(i)
print newlist

Another way with map

word_list = { "hello" : "1"}

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

for key, value in word_list.items():
  newlist=map(lambda x: x.replace(key,value), sentence)
print newlist

Another way with a list comprehension

word_list = { "hello" : "1"}

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

for key, value in word_list.items():
  newlist=[x.replace(key,value) for x in sentence]
print newlist

note: updated for python3, thanks @MGM

Upvotes: 2

tobias_k
tobias_k

Reputation: 82889

Using str.replace is problematic, as a word could be a part of another word. Better use re.sub with regular expression \b\w+\b, with \b being "word boundary", and use a callback function to get the replacement from the dictionary (or the word itself, if it is not in the dict).

>>> word_list = { "hello" : "1", "bye" : "2", 'you': "3"}
>>> sentence= ['hello you, hows things', 'you is not yourself', 'hello, good thanks']
>>> [re.sub(r'\b\w+\b', lambda m: word_list.get(m.group(), m.group()), s) for s in sentence]
['1 3, hows things', '3 is not yourself', '1, good thanks']

Also, not that by assigning to i within the loop, you are only changing the value bound to the variable i; you are not changing the string in the list! For this, you have to assign to the list element at that index, or use a list comprehension, as in my example.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Using regex:

>>> word_list = { "hello" : "1", "bye" : "2"}
>>> sentence= ['hello you, hows things', 'hello, good thanks']
>>> [re.sub('|'.join(word_list.keys()), lambda x: word_list[x.group()], i) for i in sentence]
['1 you, hows things', '1, good thanks']
>>> 

Upvotes: 0

Jithin
Jithin

Reputation: 1712

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

Upvotes: 4

steven
steven

Reputation: 236

I ran your code verbatim and it worked, but only prints the last "i". If you move the print into the for loop you get what you expected.

word_list = { "hello" : "1"}

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

output:

1 you, hows things
1, good thanks

Upvotes: 0

Related Questions