Open In App

Python – Remove Dictionary Key Words

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

Sometimes, while working with Python strings, we can have a problem in which we need to remove all the words from a string that is part of the key of the dictionary. This problem can have applications 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 the above functions can be used to solve this problem. In this, we perform the task of converting a string to a list of words using split(). Then we perform a replacement of a word present in a string with an empty string using replace() function. 

Python3




# 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))


Output : 

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

Time Complexity: O(n)
Auxiliary Space: O(n), where n is the length of string.

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. 

Python3




# 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))


Output : 

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

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

Method #3: Using keys(),split() methods and in operator

Python3




# 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))
 
# Iitializing Dictionary
test_dict = {'geeks' : 1, 'best': 6}
 
# Remove Dictionary Key Words
# uing join() + split()
temp = test_str.split(' ')
temp1 = [word for word in temp if word.lower() not in test_dict]
res = ' '.join(temp1)
 
# Pinting result
print("The string after replace : " + str(res))


Output

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

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

Method #4: Using List Comprehension and Join() Method

In this method, use a list comprehension to iterate over the words in the string and check if each word is not a key in the dictionary. If it is not a key, add it to a new list. Finally, join the new list with spaces to get the modified string.

Python




# Python3 code to demonstrate working of
# Remove Dictionary Key Words
# Using List Comprehension and Join() Method
 
# 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 List Comprehension and Join() Method
new_list = [word for word in test_str.split() if word not in test_dict.keys()]
test_str = " ".join(new_list)
 
# Printing result
print("The string after replace : " + str(test_str))


Output

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

Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n), where n is the length of the string (used for creating the new list).

Method #5: Using filter() + lambda function

  1. Firstly, the program initializes a string variable test_str with the value ‘gfg is best for geeks’.
  2. It then prints the original string using the print() function and concatenation of string and variable using + operator.
  3. The program then initializes a dictionary variable test_dict with the key-value pairs of {‘geeks’: 1, ‘best’: 6}.
  4. To remove the words from the string which are keys in the dictionary, the program uses the filter() function with a lambda function as a condition.
  5. The filter() function is called with the lambda function lambda word: word not in test_dict.keys() which takes each word from the string as an argument and checks if it is present in the keys of the test_dict dictionary.
  6. The split() method is used on the test_str variable to convert the string into a list of words.
  7. The filter() function returns an iterable object which is then converted into a list using the list() function.
  8. The join() method is then used on the returned list with the separator as a space ‘ ‘ to convert the list of words back to a string with the removed key words.
  9. Finally, the program prints the modified string using the print() function and concatenation of string and variable using + operator.

Python3




# Python3 code to demonstrate working of
# Remove Dictionary Key Words
# Using filter() + lambda function
 
# 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 filter() + lambda function
new_list = list(filter(lambda word: word not in test_dict.keys(), test_str.split()))
test_str = " ".join(new_list)
 
# Printing result
print("The string after replace : " + str(test_str))


Output

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

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string.

Method 6:  Using the re module 

Explanation:

  1. Import the re module.
  2. Initialize the input string test_str and print it.
  3. Initialize the dictionary test_dict with keys to be removed from the string.
  4. Create a regular expression pattern by joining the keys of the dictionary using the | operator. This pattern will match any of the keys in the dictionary.
  5. Use the re.sub() method to replace all occurrences of the pattern in the input string with an empty string ”.
  6.  The updated string is stored back in the test_str variable.
  7. Print the updated string.

Python3




# Python3 code to demonstrate working of
# Remove Dictionary Key Words
# Using re.sub() method
 
# import re module
import re
 
# 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 re.sub() method
pattern = '|'.join(test_dict.keys())
test_str = re.sub(pattern, '', test_str)
 
# printing result
print("The string after replace : " + str(test_str))


Output

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

Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(1), as we are only using a constant amount of extra space to store the regular expression pattern.



Similar Reads

Python - Create a Dictionary with Key as First Character and Value as Words Starting with that Character
In this article, we will code a python program to create a dictionary with the key as the first character and value as words starting with that character. Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds t
6 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python Program to Remove Nth element from Kth key's value from the dictionary
Given a dictionary with value lists, our task is to write a Python program to remove N element from Kth key's values. Examples: Input : test_dict = {"gfg" : [9, 4, 5, 2, 3, 2], "is" : [1, 2, 3, 4, 3, 2], "best" : [2, 2, 2, 3, 4]}, K, N = "gfg", 2Output : {'gfg': [9, 4, 5, 3], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}Explanation : 2 removed
9 min read
Python | Remove item from dictionary when key is unknown
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Let's discuss the various ways to remove items from the dictionary when key is unknown. Method #1 : Using n
6 min read
Python - Remove Key from Dictionary List
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove a specific key from a dictionary list. This kind of problem is very common and has application in almost all domains including day-day programming and web development domain. Let's discuss certain ways in which this task can be performed. Method #1 :
7 min read
Python - Remove K valued key from Nested Dictionary
Sometimes, while working with records, we can have a problem in which we need to perform the removal of a key from nested dictionary whose value us specific to K. This is a common problem and has its application in data domains such as web development. Lets discuss certain ways in which this task can be performed. Input : test_dict = {'CS': {'price
8 min read
Python - Remove dictionary if given key's value is N
Given list of dictionaries, remove dictionary whose Key K is N. Input : test_list = [{"Gfg" : 3, "is" : 7, "Best" : 8}, {"Gfg" : 9, "is" : 2, "Best" : 9}, {"Gfg" : 5, "is" : 4, "Best" : 10}, {"Gfg" : 3, "is" : 6, "Best" : 15}], K = "Gfg", N = 9 Output : [{"Gfg" : 3, "is" : 7, "Best" : 8}, {"Gfg" : 5, "is" : 4, "Best" : 10}, {"Gfg" : 3, "is" : 6, "B
5 min read
Python - Remove Kth key from dictionary
Many times, while working with Python, we can have a situation in which we require to remove the Kth key of the dictionary. This is useful for Python version 3.8 +, where key ordering is similar to the insertion order. Let’s discuss certain ways in which this task can be performed. Examples: Input : test_dict = {"Gfg" : 20, "is" : 36, "best" : 100,
6 min read
Remove Dictionary from List If Key is Equal to Value in Python
Removing dictionaries from a list based on a specific condition is a common task in Python programming. This operation is useful when working with data represented as a list of dictionaries, and it allows for a more streamlined and refined dataset. In this article, we will explore three concise methods to achieve this task using Python Example: Inp
3 min read
three90RightbarBannerImg