Sunday, November 17, 2024
Google search engine
HomeLanguagesPython – Remove Dictionary Key Words

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 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 Lazyroar'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing Dictionary
test_dict = {'Lazyroar': 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 Lazyroar
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 Lazyroar'
 
# Printing original string
print("The original string is : " + str(test_str))
 
# Initializing Dictionary
test_dict = {'Lazyroar': 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 Lazyroar
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 Lazyroar'
 
# Printing original string
print("The original string is : " + str(test_str))
 
# Iitializing Dictionary
test_dict = {'Lazyroar' : 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 Lazyroar
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 Lazyroar'
 
# Printing original string
print("The original string is : " + str(test_str))
 
# Initializing Dictionary
test_dict = {'Lazyroar' : 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 Lazyroar
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 Lazyroar’.
  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 {‘Lazyroar’: 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 Lazyroar'
 
# Printing original string
print("The original string is : " + str(test_str))
 
# Initializing Dictionary
test_dict = {'Lazyroar' : 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 Lazyroar
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 Lazyroar'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing Dictionary
test_dict = {'Lazyroar' : 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 Lazyroar
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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments