How to replace words in a string using a dictionary mapping
Last Updated :
12 Mar, 2025
In Python, we often need to replace words in a string based on a dictionary mapping, where keys are words to replace and values are their replacements. For example, given the string "the quick brown fox jumps over the lazy dog" and the dictionary {"quick": "slow", "lazy": "active"}, we want to replace "quick" with "slow" and "lazy" with "active". Let's discuss several methods to achieve this in Python.
Using split() and join()
This method splits the string into words, replaces the words if they exist in the dictionary and then joins them back to form the modified string.
Python
s = "the quick brown fox jumps over the lazy dog"
d = {"quick": "slow", "lazy": "active"}
# Replacing words using split and join
words = s.split() # Splitting the string into words
res = " ".join([d[w] if w in d else w for w in words]) # Replacing and joining
print(res)
Outputthe slow brown fox jumps over the active dog
Explanation:
- The string is split into individual words using split().
- Each word is checked in the dictionary and if found then it is replaced with the corresponding value.
- The modified words are joined back into a single string using join().
Let's explore some more ways and see how we can replace words in a string using a dictionary mapping.
Using regular expressions
This method uses regular expressions to search for and replace words in the string based on the dictionary mapping.
Python
import re
s = "the quick brown fox jumps over the lazy dog"
d = {"quick": "slow", "lazy": "active"}
# Defining a function for replacement
def replace_func(match):
return d[match.group(0)] # Returning the replacement from the dictionary
# Replacing words using re.sub
pattern = re.compile("|".join(re.escape(k) for k in d)) # Creating a pattern for all keys
res = pattern.sub(replace_func, s) # Replacing using the pattern
print(res)
Outputthe slow brown fox jumps over the active dog
Explanation:
- A regular expression pattern is created for all keys in the dictionary.
sub()
function replaces matching words using a custom replacement function.- This approach is efficient for longer strings and when the dictionary contains many keys.
Using string replace()
This method iteratively replaces each key in the dictionary with its corresponding value using string replace() method.
Python
s = "the quick brown fox jumps over the lazy dog"
d = {"quick": "slow", "lazy": "active"}
# Replacing words using replace in a loop
for k, v in d.items(): # Iterating through the dictionary
s = s.replace(k, v) # Replacing each key with its value
print(s)
Outputthe slow brown fox jumps over the active dog
Explanation:
- Each key-value pair in the dictionary is iterated over.
- replace method replaces all occurrences of the key with the value.
- This method is simpler but less efficient for larger dictionaries.
Using list comprehension
This method uses a custom function along with list comprehension to check and replace words in the string.
Python
s = "the quick brown fox jumps over the lazy dog"
d = {"quick": "slow", "lazy": "active"}
# Defining a custom function for replacement
def replace_words(s, d):
words = s.split() # Splitting the string into words
return " ".join([d[w] if w in d else w for w in words]) # Replacing and joining
# Using the custom function
res = replace_words(s, d) # Replacing words
print(res)
Outputthe slow brown fox jumps over the active dog
Explanation:
- custom function splits the string, checks each word in the dictionary and performs the replacement.
- This method is modular and reusable but slightly less efficient than direct split and join.
Using translation dictionary for single characters
This method is applicable when replacing single characters using a dictionary mapping.
Python
s = "the quick brown fox jumps over the lazy dog"
d = {"t": "T", "q": "Q"}
# Replacing characters using translate
res = s.translate(str.maketrans(d)) # Translating using the mapping
print(res)
OutputThe Quick brown fox jumps over The lazy dog
Explanation:
- translate() method is specifically designed for replacing single characters.
- A translation table is created using maketrans() and the replacements are applied.
- This method is efficient for single-character replacements.
Similar Reads
Replacing Characters in a String Using Dictionary in Python In Python, we can replace characters in a string dynamically based on a dictionary. Each key in the dictionary represents the character to be replaced, and its value specifies the replacement. For example, given the string "hello world" and a dictionary {'h': 'H', 'o': 'O'}, the output would be "Hel
2 min read
How to replace a word in excel using Python? Excel is a very useful tool where we can have the data in the format of rows and columns. We can say that before the database comes into existence, excel played an important role in the storage of data. Nowadays using Excel input, many batch processing is getting done. There may be the requirement o
3 min read
Python | Ways to invert mapping of dictionary Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Let's discuss a few ways to invert mapping of a dictionar
3 min read
Python | Words extraction from set of characters using dictionary Given the words, the task is to extract different words from a set of characters using the defined dictionary. Approach: Python in its language defines an inbuilt module enchant which handles certain operations related to words. In the approach mentioned, following methods are used. check() : It che
3 min read
Word Dictionary using Tkinter Prerequisite: TkinterPydictionary Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. In this article, we will learn how to mak
2 min read
How to Change the name of a key in dictionary? Dictionaries in Python are a versatile and powerful data structure, allowing you to store key-value pairs for efficient retrieval and manipulation. Sometimes, you might need to change the name of a key in a dictionary. While dictionaries do not directly support renaming keys, there are several ways
4 min read