Open In App

How to replace words in a string using a dictionary mapping

Last Updated : 12 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)  

Output
the 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) 

Output
the 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)

Output
the 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)  

Output
the 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) 

Output
The 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.

Next Article
Article Tags :
Practice Tags :

Similar Reads