Open In App

Python – Replace words from Dictionary

Last Updated : 03 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given String, replace it’s words from lookup dictionary.

Input : test_str = ‘geekforgeeks best for geeks’, repl_dict = {“geeks” : “all CS aspirants”} 
Output : geekforgeeks best for all CS aspirants 
Explanation : “geeks” word is replaced by lookup value. 

Input : test_str = ‘geekforgeeks best for geeks’, repl_dict = {“good” : “all CS aspirants”} 
Output : geekforgeeks best for geeks 
Explanation : No lookup value, unchanged result.

Method #1 : Using split() + get() + join()

In this, we initially split the list using split(), then look for lookups using get(), and if found, replaced and joined back to string using join().

Python3




# Python3 code to demonstrate working of
# Replace words from Dictionary
# Using split() + join() + get()
 
# initializing string
test_str = 'geekforgeeks best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# lookup Dictionary
lookp_dict = {"best" : "good and better", "geeks" : "all CS aspirants"}
 
# performing split()
temp = test_str.split()
res = []
for wrd in temp:
     
    # searching from lookp_dict
    res.append(lookp_dict.get(wrd, wrd))
     
res = ' '.join(res)
 
# printing result
print("Replaced Strings : " + str(res))


Output

The original string is : geekforgeeks best for geeks
Replaced Strings : geekforgeeks good and better for all CS aspirants

Time Complexity: O(N), where N is the length of the input string.

Auxiliary Space: O(N)

Method #2 : Using list comprehension + join()

Similar to above method, difference just being 1 liner rather than 3-4 steps in separate lines.

Python3




# Python3 code to demonstrate working of
# Replace words from Dictionary
# Using list comprehension + join()
 
# initializing string
test_str = 'geekforgeeks best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# lookup Dictionary
lookp_dict = {"best" : "good and better", "geeks" : "all CS aspirants"}
 
# one-liner to solve problem
res = " ".join(lookp_dict.get(ele, ele) for ele in test_str.split())
 
# printing result
print("Replaced Strings : " + str(res))


Output

The original string is : geekforgeeks best for geeks
Replaced Strings : geekforgeeks good and better for all CS aspirants

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3: Using a for loop and a temporary list

  • Initialize the lookup dictionary variable lookp_dict with the key-value pairs “best” : “good and better” and “geeks” : “all CS aspirants”.
  • Create an empty list called temp that will hold the replaced strings.
  • Split the input string into a list of words using the split() method and iterate over each word using a for loop.
  • For each word, check if it exists in the lookup dictionary using the get() method. If it does, append the corresponding value to the temp list, otherwise append the original word.
  • Join the temp list using the join() method and separate the words with a space character. Assign this string to the variable res.
  • Print the final result using print(“Replaced Strings : ” + str(res)).

Python3




# initializing string
test_str = 'geekforgeeks best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# lookup Dictionary
lookp_dict = {"best" : "good and better", "geeks" : "all CS aspirants"}
 
# create a temporary list to hold the replaced strings
temp = []
for word in test_str.split():
    temp.append(lookp_dict.get(word, word))
 
# join the temporary list to create the final output string
res = " ".join(temp)
 
# printing result
print("Replaced Strings : " + str(res))


Output

The original string is : geekforgeeks best for geeks
Replaced Strings : geekforgeeks good and better for all CS aspirants

Time complexity: O(n), where n is the number of words in the input string.
Auxiliary space: O(n), where n is the number of words in the input string (due to the creation of the temporary list).



Similar Reads

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 : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python - Replace multiple words with K
Sometimes, while working with Python strings, we can have a problem in which we need to perform a replace of multiple words with a single word. This can have application in many domains including day-day programming and school programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using join() + split() + list compr
7 min read
Python - Replace all words except the given word
Given a string. The task is to replace all the words with '?' except the given word K. Examples: Input : test_str = 'gfg is best for geeks', K = "gfg", repl_char = "?" Output : gfg ? ? ? ? Explanation : All words except gfg is replaced by ?. Input : test_str = 'gfg is best for gfg', K = "gfg", repl_char = "?" Output : gfg ? ? ? gfg Explanation : Al
6 min read
Python - Compute the frequency of words after removing stop words and stemming
In this article we are going to tokenize sentence, paragraph, and webpage contents using the NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentences, paragraphs, and webpage. Finally, we will Compute the frequency of words after removing stop words and stemming. Modules Needed bs4: Beaut
8 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. Input : test_list = ["Gfg", "is", "Best"], subs_dict
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 empty dictionaries. Input : test_dict = {"Gfg" : {7
4 min read
Python - Replace value by Kth index value in Dictionary List
Given a dictionary list, the task is to write a Python program to replace the value of a particular key with kth index of value if the value of the key is list. Examples: Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : [7, 3, 9, 1]}], K = 2, key = "gfg" Output : [{'gfg':
7 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 checks if a string is a word or not and returns true
3 min read
three90RightbarBannerImg