Python - Replace words from Dictionary
Replacing words in a string using a dictionary allows us to efficiently map specific words to new values.
Using str.replace()
in a Loop
Using str.replace()
in a loop, you can systematically replace specific substrings within a string with new values. This approach is useful for repetitive replacements, such as modifying multiple words or characters.
# Input string
s = "hello world, have a great day"
# Dictionary of words to replace
r_dict = {"hello": "hi", "world": "earth", "great": "wonderful"}
# Replace words in the string using a loop
for o_word, n_word in r_dict.items():
s = s.replace(o_word, n_word)
# Print the result
print(s)
Output
hi earth, have a wonderful day
Explanation
r_dict
dictionary defines the words to replace as keys and their corresponding new words as values. By iterating through the dictionary, each key-value pair is used to replace occurrences in the input string.str.replace()
method is applied in each iteration to replace the old word (o_word
) with the new word (n_word
).
Let's understand various other methods to Replace words from Dictionary
Table of Content
Using Regular Expressions (re.sub()
)
This method uses re.sub()
with a dynamically created regex pattern to find all target words in the string. A lambda function is used for on-the-fly substitution, replacing each matched word with its corresponding value from the dictionary.
import re
# Input string
s = "hello world, have a great day"
# Dictionary of words to replace
r_dict = {"hello": "hi", "world": "earth", "great": "wonderful"}
# Replace words using re.sub with a function
result = re.sub(r'\b(?:' + '|'.join(r_dict.keys()) + r')\b',
lambda match: r_dict[match.group()], s)
# Print the result
print(result)
Output
hi earth, have a wonderful day
Explanation
- The code constructs a regex pattern dynamically to match whole words from the dictionary keys using
re.sub()
. - A lambda function is used to replace each matched word with its corresponding value from the dictionary
Using List Comprehension
Using list comprehension provides a concise and efficient way to replace words in a string. By iterating through each word, it checks if the word exists in a dictionary and replaces it, otherwise keeping the original word.
# Input string
s = "hello world, have a great day"
# Dictionary of words to replace
r_dict = {"hello": "hi", "world": "earth", "great": "wonderful"}
# Replace words using list comprehension and join
result = ' '.join([r_dict.get(word, word) for word in s.split()])
# Print the result
print(result)
Output
hi world, have a wonderful day
Explanation
- The string is split into words, and list comprehension iterates through each word.
- For each word, it checks if it's in the dictionary
r_dict
. If it is, it replaces it; otherwise, the original word remains. - The words are then joined back into a string using
' '.join()
and printed.
Using str.split()
and map()
str.split()
method divides the string into words, and map()
applies a replacement function to each word using the dictionary. Finally, the modified words are joined back into a string.
s = "hello world, have a great day"
# Dictionary of words to replace
r_dict = {"hello": "hi", "world": "earth", "great": "wonderful"}
# Replace words using split and map
result = ' '.join(map(lambda word: r_dict.get(word, word), s.split()))
# Print the result
print(result)
Output
hi world, have a wonderful day
Explanation
- The
str.split()
method breaks the string into words, andmap()
applies a function to replace each word using the dictionary. - The
lambda
function checks if the word exists in the dictionary; if it does, it replaces it, otherwise, it keeps the original word.