VOOZH about

URL: https://www.geeksforgeeks.org/python/python-replace-words-from-dictionary/

⇱ Python - Replace words from Dictionary - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Replace words from Dictionary

Last Updated : 15 Jul, 2025

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.


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

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.


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.


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.


Output
hi world, have a wonderful day

Explanation

  • The str.split() method breaks the string into words, and map() 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.
Comment