Learner91
Learner91

Reputation: 123

Cant replace all the word with replacement in python based on the match in dictionary list

I tried to replace the word in a string with the value in a dictionary if its matched.

My code:

test_dict = {"valuation": "none", "other": "test"}
for word, replacement in test_dict.items():
    if word in "other valuation $$$":
        strValue = "other valuation $$$".replace(word, replacement)

My current output:

'test valuation $$$'

My expected output:

'test none $$$'

is there a way to do it in single line? If not any types is fine.

Upvotes: 0

Views: 38

Answers (1)

Sharim09
Sharim09

Reputation: 6214

This is because you change the strValue value back to the initial string.

test_dict = {"valuation": "none", "other": "test"}
strValue = "other valuation $$$"
for word, replacement in test_dict.items():
    strValue = strValue.replace(word, replacement)
print(strValue)

You can do the same in one line also but it also makes list with None values.

test_dict = {"valuation": "none", "other": "test"}
strValue = ["other valuation $$$"]


[strValue.append(strValue[-1].replace(word,replacement)) for word,replacement in test_dict.items()]

print(strValue[-1])

output

test none $$$

Upvotes: 1

Related Questions