Python – Remove Dictionary Key Words

Sometimes, while working with Python strings, we can have a problem in which we need to remove all the words from a string which are a part of key of dictionary. This problem can have application in domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using split() + loop + replace()
The combination of above functions can be used to solve this problem. In this, we perform the task of converting string to list of words using split(). Then we perform a replace of word present in string with empty string using replace().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Remove Dictionary Key Words
# Using split() + loop + replace()
  
# initializing string
test_str = 'gfg is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing Dictionary
test_dict = {'geeks' : 1, 'best': 6}
  
# Remove Dictionary Key Words
# Using split() + loop + replace()
for key in test_dict:
    if key in test_str.split(' '):
        test_str = test_str.replace(key, "")
  
# printing result 
print("The string after replace : " + str(test_str)) 

chevron_right


Output :

The original string is : gfg is best for geeks
The string after replace : gfg is  for 

 

Method #2 : Using join() + split()
This is yet another way in which this task can be performed. In this, we reconstruct new string using join(), performing join by the empty string after split.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Remove Dictionary Key Words
# Using join() + split()
  
# initializing string
test_str = 'gfg is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing Dictionary
test_dict = {'geeks' : 1, 'best': 6}
  
# Remove Dictionary Key Words
# Using join() + split()
temp = test_str.split(' ')
temp1 = [word for word in temp if word.lower() not in test_dict]
res = ' '.join(temp1)
  
# printing result 
print("The string after replace : " + str(res)) 

chevron_right


Output :

The original string is : gfg is best for geeks
The string after replace : gfg is  for 



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.