Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace key in a senetence with its value

I have a dictionary and a list

dict1= {'good':'bad','happy':'sad','pro':'anti'}
list1=['she is good','this is a product','they are pro choice']
newlist=[]
for index, data in enumerate(list1):
    for key, value in dict1.items():
        if key in data:
            list1[index]=data.replace(key, dict1[key])
            newlist.append(list1[index])
The output I get is
['she is bad','this is a antiduct','they are anti choice']

desired output is
['she is bad','this is a product','they are anti choice']

How can I fix it? It is replacing the pro of prodcut too. I only want it to replace pro when it exists as an independent word.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One option would be to split each phrase and do the substitution with a straight get on the dictionary, rather than a replace:

>>> dict1= {'good':'bad','happy':'sad','pro':'anti'}
>>> list1={'she is good','this is a product','they are pro choice'}
>>> [' '.join(dict1.get(word, word) for word in phrase.split()) for phrase in list1]
['this is a product', 'she is bad', 'they are anti choice']

Note that this will not preserve whitespace in the phrase, nor will it handle punctuation very well. re and itertools.groupby would be useful tools to handle those more complex cases.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading