Open In App

Python | Remove Keys from dictionary starting with K

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

Sometimes, while working with dictionaries, we can have a particular use case in which we need to remove certain keys. There can be many criteria upon which we may need to perform this task. One such criteria can be removed on basis of starting the substring. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using Naive method + startswith() + pop() 

This particular task can be performed using a combination of the above functions, which is a brute-force method to perform this task. The pop function is used to remove the key-value pair and startswith provide the condition upon which this has to be performed. 

Python3




# Python3 code to demonstrate working of
# Remove Keys from dictionary starting with K
# Using Naive Method + startswith() + pop()
 
# initializing dictionary
test_dict = {"Apple": 1, "Star": 2, "App": 4, "Gfg": 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing Substring
K = "Ap"
 
# Using Naive Method + startswith() + pop()
# Remove Keys from dictionary starting with K
res = list(test_dict.keys())
for key in res:
  if key.startswith(K):
      test_dict.pop(key)
 
# printing result
print("Dictionary after key removal : " + str(test_dict))


Output

The original dictionary is : {'Apple': 1, 'Star': 2, 'App': 4, 'Gfg': 3}
Dictionary after key removal : {'Star': 2, 'Gfg': 3}

The time complexity of this code is O(n^2) because we are using a loop to iterate over all the keys in the dictionary.

The auxiliary space complexity of this code is O(n) because we are creating a list of all the keys in the dictionary using the keys() method.

Method #2: Using list comprehension + dict() + startswith() + items() 

There is also 1 liner alternative to perform this particular task in which we get all the keys and values using items() and then reconstruct the dictionary with keys that do not start with K using startswith function. The dict function at the end performs the conversion from list to dictionary. 

Python3




# Python3 code to demonstrate working of
# Remove Keys from dictionary starting with K
# Using list comprehension + dict() + startswith() + items()
 
# initializing dictionary
test_dict = {"Apple": 1, "Star": 2, "App": 4, "Gfg": 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing Substring
K = "Ap"
 
# Using list comprehension + dict() + startswith() + items()
# Remove Keys from dictionary starting with K
res = dict([(x, y) for x, y in test_dict.items() if not x.startswith(K)])
 
# printing result
print("Dictionary after key removal : " + str(res))


Output

The original dictionary is : {'Apple': 1, 'Star': 2, 'App': 4, 'Gfg': 3}
Dictionary after key removal : {'Star': 2, 'Gfg': 3}

Time complexity: O(n), where n is the number of key-value pairs in the original dictionary.

Auxiliary space: O(n), where n is the number of key-value pairs in the original dictionary. 

Method #3 : Using keys() and find() methods

Python3




# Python3 code to demonstrate working of
# Remove Keys from dictionary starting with K
 
# initializing dictionary
test_dict = {"Apple" : 1, "Star" : 2, "App" : 4, "Gfg" : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing Substring
K = "Ap"
 
d=dict()
for i in list(test_dict.keys()):
    if(i.find(K)!=0):
        d[i]=test_dict[i]
         
# printing result
print("Dictionary after key removal : " + str(d))


Output

The original dictionary is : {'Apple': 1, 'Star': 2, 'App': 4, 'Gfg': 3}
Dictionary after key removal : {'Star': 2, 'Gfg': 3}

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.

Method #4 : Using keys(),len() methods and slicing

Python3




# Python3 code to demonstrate working of
# Remove Keys from dictionary starting with K
 
# Initializing dictionary
test_dict = {"Apple" : 1, "Star" : 2, "App" : 4, "Gfg" : 3}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initializing Substring
K = "G"
 
d=dict()
for i in list(test_dict.keys()):
    if(i[:len(K)]!=K):
        d[i]=test_dict[i]
         
# Printing result
print("Dictionary after key removal : " + str(d))


Output

The original dictionary is : {'Apple': 1, 'Star': 2, 'App': 4, 'Gfg': 3}
Dictionary after key removal : {'Apple': 1, 'Star': 2, 'App': 4}

Method #2: Using Regular Expression

Regular expressions are special texts which are used for pattern matching. We can use regular expressions as a way to perform this task. A regular expression can be used to match a substring. We can combine this regular expression with a for loop to perform this task. This can be used to perform a more efficient task of removing key-value pairs from a dictionary. 

Python3




# Python3 code to demonstrate working of
# Remove Keys from dictionary starting with K
# Using Regular Expression
 
# initializing dictionary
test_dict = {"Apple": 1, "Star": 2, "App": 4, "Gfg": 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing Substring
K = "Ap"
 
# Using Regular Expression
# Remove Keys from dictionary starting with K
import re
 
res = list(test_dict.keys())
for key in res:
    if re.match("^" + K, key):
        test_dict.pop(key)
 
# printing result
print("Dictionary after key removal : " + str(test_dict))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original dictionary is : {'Apple': 1, 'Star': 2, 'App': 4, 'Gfg': 3}
Dictionary after key removal : {'Star': 2, 'Gfg': 3}

Time complexity: O(n)
Auxiliary Space: O(1)

Method #6: Using filter and lambda function:

Step-by-step approach:

  • Initialize a dictionary with some key-value pairs.
  • Print the original dictionary.
  • Initialize a substring K.
  • Use the filter() function along with a lambda function to filter the keys of the dictionary based on whether they start with the substring K, this returns a list of keys that start with K.
  • Convert the filtered keys to a list.
  • Use a for loop to iterate over the keys that need to be removed.
    • Use the pop() function to remove the key-value pairs from the dictionary.
  • Print the resulting dictionary.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Remove Keys from dictionary starting with K
# Using filter and lambda() function
 
# initializing dictionary
test_dict = {"Apple": 1, "Star": 2, "App": 4, "Gfg": 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing Substring
K = "Ap"
 
#filtering keys
keys_to_remove = list(filter(lambda key: key.startswith(K), test_dict.keys()))
 
# removing keys
for key in keys_to_remove:
   test_dict.pop(key)
 
# printing result
print("Dictionary after key removal : " + str(test_dict))


Output

The original dictionary is : {'Apple': 1, 'Star': 2, 'App': 4, 'Gfg': 3}
Dictionary after key removal : {'Star': 2, 'Gfg': 3}

Time complexity: O(n) as we are traversing the dictionary.
Auxiliary Space: O(1) as no extra memory is required.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads