Open In App

Python – Remove keys with substring values

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 geeks’} 
sub_list = [‘love’, ‘good’] ( Strings to check in values ) 
Output : {1: ‘Gfg is best for geeks’}

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 geeks', 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 geeks’, 2: ‘Gfg is good’, 3: ‘I love Gfg’} 
Filtered Dictionary: {1: ‘Gfg is best for geeks’} 
 

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 geeks', 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 geeks', 2: 'Gfg is good', 3: 'I love Gfg'}
Filtered Dictionary : {1: 'Gfg is best for geeks'}

 

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 geeks', 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 geeks', 2: 'Gfg is good', 3: 'I love Gfg'}
Filtered Dictionary : {1: 'Gfg is best for geeks'}

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 geeks', 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 geeks', 2: 'Gfg is good', 3: 'I love Gfg'}
Filtered Dictionary : {1: 'Gfg is best for geeks'}

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.



Similar Reads

Python - Remove keys with Values Greater than K ( Including mixed values )
Given a dictionary with key-value pairs, remove all the keys with values greater than K, including mixed values. Input : test_dict = {'Gfg' : 3, 'is' : 7, 'best' : 10, 'for' : 6, 'geeks' : 'CS'}, K = 7 Output : {'Gfg' : 3, 'for' : 6, 'geeks' : 'CS'} Explanation : All values greater than K are removed. Mixed value is retained. Input : test_dict = {'
4 min read
Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Python - Remove duplicate values across Dictionary Values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the duplicate values across all the dictionary value lists. This problem can have applications in data domains and web development domains. Let's discuss certain ways in which this task can be performed. Input: test_dict = {'Manjeet': [1], 'Akash
8 min read
Python | Split dictionary keys and values into separate lists
Given a dictionary, the task is to split a dictionary in python into keys and values into different lists. Let's discuss the different ways we can do this. Example Input: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} Output: keys: ['a', 'b', 'c'] values: ['akshat', 'bhuvan', 'chandan']Method 1: Split dictionary keys and values using inbuilt functi
5 min read
Python program to Swap Keys and Values in Dictionary
Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value so that they can be retrieved efficiently. Let’s discuss various ways of swapping the keys and values in Python Dictionary. Method#1 (Does not work when there are multiple same values): One naive solution maybe something like just swa
4 min read
Python - Test if Values Sum is Greater than Keys Sum in dictionary
Given a Dictionary, check if the summation of values is greater than the keys sum. Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5} Output : False Explanation : Values sum = 19 < 40, which is key sum, i.e false.Input : test_dict = {5:3, 1:4} Output : True Explanation : Values sum = 7 > 6, which is key sum, i.e true. Method #1: Using loop I
8 min read
Python | Find keys with duplicate values in dictionary
Given a dictionary, the task is to find keys with duplicate values. Let's discuss a few methods for the same. Method #1: Using Naive approach In this method first, we convert dictionary values to keys with the inverse mapping and then find the duplicate keys C/C++ Code # Python code to demonstrate # finding duplicate values from a dictionary # init
4 min read
Python | Combine two dictionary adding values for common keys
Given two dictionaries, the task is to combine the dictionaries such that we get the added values for common keys in the resultant dictionary. Example: Input: dict1 = {'a': 12, 'for': 25, 'c': 9} dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} Output: {'for': 325, 'Geeks': 100, 'geek': 200} Let's see some of the methods on How to Combine two dictio
4 min read
Python | Test if dictionary contains unique keys and values
Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it
6 min read
Practice Tags :