Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Remove keys with substring values

Python – Remove keys with substring values

Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove keys whose values have substring as argument we pass. This problem can occur in cases of web development and day-day programming. Lets discuss certain ways in which this task can be performed.
 

Input
test_dict = {1 : ‘Gfg is best for Lazyroar’} 
sub_list = [‘love’, ‘good’] ( Strings to check in values ) 
Output : {1: ‘Gfg is best for Lazyroar’}

Input
test_dict = {1 : ‘Gfg is love’, 2: ‘Gfg is good’} 
sub_list = [‘love’, ‘good’] ( Strings to check in values ) 
Output : {} 

Method #1 : Using any() + loop 

The combination of above functionalities can be used to solve this problem. In this, we extract all the items from dictionary which do not have desired values, the filtration is performed using any() and generator expression.

Python3




# Python3 code to demonstrate working of
# Remove keys with substring values
# Using any() + generator expression
 
# initializing dictionary
test_dict = {1 : 'Gfg is best for Lazyroar', 2 : 'Gfg is good', 3 : 'I love Gfg'}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# initializing substrings
sub_list = ['love', 'good']
 
# Remove keys with substring values
# Using any() + generator expression
res = dict()
for key, val in test_dict.items():
   if not any(ele in val for ele in sub_list):
       res[key] = val
        
# printing result
print("Filtered Dictionary : " + str(res))


Output : 
The original dictionary: {1: ‘Gfg is best for Lazyroar’, 2: ‘Gfg is good’, 3: ‘I love Gfg’} 
Filtered Dictionary: {1: ‘Gfg is best for Lazyroar’} 
 

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

Method #2 : Using dictionary comprehension + any() 

The combination of above methods provide the shorthand to execute this task. In this, we perform this task in similar way as above method, but in one liner format using comprehension.

Python3




# Python3 code to demonstrate working of
# Remove keys with substring values
# Using dictionary comprehension + any()
 
# initializing dictionary
test_dict = {1 : 'Gfg is best for Lazyroar', 2 : 'Gfg is good', 3 : 'I love Gfg'}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# initializing substrings
sub_list = ['love', 'good']
 
# Remove keys with substring values
# Using dictionary comprehension + any()
res = {key : val for key, val in test_dict.items() if not any(ele in val for ele in sub_list)}
        
# printing result
print("Filtered Dictionary : " + str(res))


Output : 

The original dictionary : {1: 'Gfg is best for Lazyroar', 2: 'Gfg is good', 3: 'I love Gfg'}
Filtered Dictionary : {1: 'Gfg is best for Lazyroar'}

 

Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Method #3: Using pop method

Approach

the pop method to remove the key-value pairs containing the substring from the original dictionary. Here’s the code for the same

Algorithm

1. Iterate over the key-value pairs in the ‘test_dict’.
2. For each value in the ‘test_dict’, iterate over the ‘sub_list’.
3. If the substring is found in the value, remove that key-value pair from the ‘test_dict’.
4. Return the ‘test_dict’ after removing the required key-value pairs.

Python3




test_dict = {1: 'Gfg is love', 2: 'Gfg is good'}
sub_list = ['love', 'good']
 
for key, value in list(test_dict.items()):
    for sub in sub_list:
        if sub in value:
            test_dict.pop(key)
 
print(test_dict)


Output

{}

Time complexity: O(n*m), where n is the number of key-value pairs in the dictionary and m is the length of the longest value string.
Auxiliary Space: O(1), as we are modifying the original dictionary.

Method 4: Using filter() + lambda 

Step-by-step approach:

  • Initializing dictionary
  • printing original dictionary
  • Initializing substrings
  • Remove keys with substring values Using filter() + lambda 
  • Printing result 

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Remove keys with substring values
# Using filter() + lambda
 
# initializing dictionary
test_dict = {1 : 'Gfg is best for Lazyroar', 2 : 'Gfg is good', 3 : 'I love Gfg'}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# initializing substrings
sub_list = ['love', 'good']
 
# Remove keys with substring values
# Using filter() + lambda
res = dict(filter(lambda item: not any(sub in item[1] for sub in sub_list), test_dict.items()))
 
# printing result
print("Filtered Dictionary : " + str(res))


Output

The original dictionary : {1: 'Gfg is best for Lazyroar', 2: 'Gfg is good', 3: 'I love Gfg'}
Filtered Dictionary : {1: 'Gfg is best for Lazyroar'}

Time complexity: O(n), where n is the number of key-value pairs in the dictionary. 
Auxiliary space: O(n), as we are creating a new dictionary to store the filtered key-value pairs.

Method 5: Using Reduce():

Algorithm:

  1. Import the reduce function from functools module.
  2. Initialize a dictionary called test_dict.
  3. Print the original dictionary.
  4. Initialize the sub_list which contains the substrings to be removed.
  5. Using the filter() function with lambda function, remove the keys with substring values from the dictionary.
    Using the reduce() function with lambda function, filter the dictionary keys that don’t have the substring values and create a new dictionary with only those keys.
    Print the filtered dictionary.

Python3




# Import reduce from functools
from functools import reduce
 
# initializing dictionary
test_dict = {1 : 'Gfg is best for Lazyroar', 2 : 'Gfg is good', 3 : 'I love Gfg'}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# initializing substrings
sub_list = ['love', 'good']
 
# Remove keys with substring values
# Using reduce() + lambda
res = reduce(lambda d, k: {**d, k: test_dict[k]}, filter(lambda k: not any(sub in test_dict[k] for sub in sub_list), test_dict), {})
 
# printing result
print("Filtered Dictionary : " + str(res))
#This code is contributed by Jyothi pinjala.


Output

The original dictionary : {1: 'Gfg is best for Lazyroar', 2: 'Gfg is good', 3: 'I love Gfg'}
Filtered Dictionary : {1: 'Gfg is best for Lazyroar'}

Time complexity:
The time complexity of the filter() function is O(n), where n is the number of elements in the dictionary. The time complexity of the reduce() function is O(n), where n is the number of elements in the dictionary. Therefore, the overall time complexity of the code is O(n).

Auxiliary Space:
The space complexity of the code is O(n), where n is the number of elements in the dictionary. This is because we are creating a new dictionary to store the filtered keys, and the size of the dictionary is proportional to the number of elements in the original dictionary.

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