Python Practice › Dictionary Programs › Program 28
Replace words using a dictionary
Write a Python program to replace words in a string using a dictionary of replacements.
Input
"learning python at sqa-tools", {"at": "is", "sqa-tools": "fun"}Output
learning python is fun
Approach
- Map each word through
d.get(word, word).
Solution
text = "learning python at sqa-tools"repl = {"at": "is", "sqa-tools": "fun"}print(" ".join(repl.get(w, w) for w in text.split()))Output
learning python is fun
Line by line
Line 3
get(w, w) returns the replacement, or the word itself when there is none.
Learn the concept
New to this topic? Read the lesson, then come back.