Write a Python program to Replace words from Dictionary


This program first defines a string variable val with the value "Tutor joe's Computer Education".

  • Then, a dictionary dic is defined, which contains two key-value pairs: "Computer" maps to "Software" and "Education" maps to "Solution".
  • Next, the program splits the val string into a list of individual words, stored in the word variable.
  • The program then creates an empty list called res. It then loops through each word in the word list and checks if the word is a key in the dic dictionary. If the word is a key in the dictionary, the corresponding value is added to the res list. If the word is not a key in the dictionary, the word itself is added to the res list.
  • Finally, the program uses the join method to combine all of the elements in the res list into a single string, separated by spaces. The resulting string is stored in the res variable and is then outputted using the second print statement:

Source Code

val = "Tutor joe's Computer Education"
print("Original string : ",val)
 
dic = {"Computer" : "Software ", "Education" : "Solution"}
 
word = val.split()
res = []
for w in word:
	res.append(dic.get(w, w))	
res = ' '.join(res)
 
print("Replaced Strings : " ,res)

Output

Original string :  Tutor joe's Computer Education
Replaced Strings :  Tutor joe's Software  Solution