Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Remove Spaces from Dictionary Keys - Python
Next article icon

Python – Replace words from Dictionary

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Python
# 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())
  • Using List Comprehension
  • Using str.split() and map()

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.

Python
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.

Python
# 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.

Python
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, 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.


Next Article
Remove Spaces from Dictionary Keys - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Remove Spaces from Dictionary Keys - Python
    Sometimes, the keys in a dictionary may contain spaces, which can create issues while accessing or processing the data. For example, consider the dictionary d = {'first name': 'Nikki', 'last name': 'Smith'}. We may want to remove spaces from the keys to standardize the dictionary, resulting in {'fir
    3 min read
  • Python - Value Dictionary from Record List
    Sometimes, while working with Python Records lists, we can have problems in which, we need to reform the dictionary taking just values of the binary dictionary. This can have applications in many domains which work with data. Let us discuss certain ways in which this task can be performed. Method #1
    6 min read
  • Python - Replace None with Empty Dictionary
    Given a dictionary, replace None values in every nesting with an empty dictionary. Input : test_dict = {"Gfg" : {1 : None, 7 : None}, "is" : None, "Best" : [1, { 5 : None }, 9, 3]} Output : {'Gfg': {1: {}, 7: {}}, 'is': {}, 'Best': [1, {5: {}}, 9, 3]} Explanation : All None values are replaced by em
    4 min read
  • Python - Remove Top level from Dictionary
    Sometimes, while working with Python Dictionaries, we can have nesting of dictionaries, with each key being single values dictionary. In this we need to remove the top level of dictionary. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed.
    3 min read
  • Python - Remove Item from Dictionary
    There are situations where we might want to remove a specific key-value pair from a dictionary. For example, consider the dictionary d = {'x': 10, 'y': 20, 'z': 30}. If we need to remove the key 'y', there are multiple ways to achieve this. Let's discuss several methods to remove an item from a dict
    3 min read
  • Python Remove Dictionary Item
    Sometimes, we may need to remove a specific item from a dictionary to update its structure. For example, consider the dictionary d = {'x': 100, 'y': 200, 'z': 300}. If we want to remove the item associated with the key 'y', several methods can help achieve this. Let’s explore these methods. Using po
    3 min read
  • Remove Kth Key from Dictionary - Python
    We are given a dictionary we need to remove Kth key from the dictionary. For example, we are given a dictionary d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'} we need to remove the key2 so that the output should be {'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}.
    3 min read
  • Python - Replace dictionary value from other dictionary
    Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "G
    6 min read
  • Python - Replace String by Kth Dictionary value
    Given a list of Strings, replace the value mapped with the Kth value of mapped list. Input : test_list = ["Gfg", "is", "Best"], subs_dict = {"Gfg" : [5, 6, 7], "is" : [7, 4, 2]}, K = 0 Output : [5, 7, "Best"] Explanation : "Gfg" and "is" is replaced by 5, 7 as 0th index in dictionary value list. Inp
    6 min read
  • Update a Dictionary in Python using For Loop
    Updating dictionaries in Python is a common task in programming, and it can be accomplished using various approaches. In this article, we will explore different methods to update a dictionary using a for loop. Update a Dictionary in Python Using For Loop in PythonBelow are some of the approaches by
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences