Open In App

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 naive + del del keyword can be used to inplace delete the key that is present in the dictionary. One drawback that can be thought of using this is that raises an exception if the key is not found and hence non-existence of key has to be handled. 






# Python code to demonstrate how to remove
# an item from the dictionary without knowing
# a key using naive + del method
 
# Initialising dictionary
test1 = {"akshat" : 21, "nikhil" : 22, "akash" : 23, "manjeet" : 27}
 
# Printing dictionary before removal
print ("Original Dictionary : " + str(test1))
 
# using naive + del method
# remove key nikhil
item_to_remove = 23
 
for key, item in test1.items():
    if item is item_to_remove:
        del test1[key]
        break
         
# Printing dictionary after removal
print ("Dictionary after remove is : " + str(test1))

Output:
Original Dictionary : {'akshat': 21, 'manjeet': 27, 'nikhil': 22, 'akash': 23}
Dictionary after remove is : {'akshat': 21, 'manjeet': 27, 'nikhil': 22}

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 #2: Using dictionary comprehension. 




# Python code to demonstrate how to remove
# item from dictionary without knowing key
# using dictionary comprehension
 
# Initialising dictionary
test1 = {"akshat" : 21, "nikhil" : 22, "akash" : 23, "manjeet" : 27}
 
# Printing dictionary before removal
print ("Original Dictionary : " + str(test1))
 
# using dictionary comprehension method
# remove key akash
value_to_remove = 23
 
res = {key: value for key, value in test1.items()
             if value is not value_to_remove}
         
# Printing dictionary after removal
print ("Dictionary after remove is : " + str(res))

Output:
Original Dictionary : {'nikhil': 22, 'akash': 23, 'akshat': 21, 'manjeet': 27}
Dictionary after remove is : {'nikhil': 22, 'manjeet': 27, 'akshat': 21}

Method #3: Using naive + pop() + naive Python language specified pop() for almost all containers, be it list, set etc. 




# Python code to demonstrate how to remove
# item from dictionary without knowing key
# using naive + pop()
 
# Initialising dictionary
test1 = {"akshat" : 21, "nikhil" : 22, "akash" : 23, "manjeet" : 27}
 
# Printing dictionary before removal
print ("Original dictionary : " + str(test1))
 
# using naive + pop()
# remove key akash
value_to_remove = 23
 
for key in test1.keys():
    if test1[key] == value_to_remove:
        test1.pop(key)
        break
         
# Printing dictionary after removal
print ("Dictionary after remove is : " + str(test1))

Output:
Original dictionary : {'manjeet': 27, 'nikhil': 22, 'akshat': 21, 'akash': 23}
Dictionary after remove is : {'manjeet': 27, 'nikhil': 22, 'akshat': 21}

Method 4: Using filter

Approach is using the filter built-in function. This function can be used to create a new dictionary with only the key-value pairs that satisfy a certain condition.

For example, to remove a key-value pair from a dictionary where the value is equal to a certain value, you can use the following code:




test1 = {"akshat": 21, "nikhil": 22, "akash": 23, "manjeet": 27}
 
# value to remove
value_to_remove = 23
 
# create a new dictionary with only the key-value pairs that don't have the value to remove
filtered_dict = dict(filter(lambda item: item[1] != value_to_remove, test1.items()))
 
print(filtered_dict)  # Output: {'akshat': 21, 'nikhil': 22, 'manjeet': 27}
#This code is contributed by Edula Vinay Kumar Reddy

Output
{'akshat': 21, 'nikhil': 22, 'manjeet': 27}

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

Method #5: Using a list comprehension and a dict() constructor to create a new dictionary without the item

Uses a dict() constructor with a list comprehension to create the new dictionary.

Follow the below steps to implement the above idea:

Below is the implementation of the above approach:




# Python code to demonstrate how to remove
# an item from the dictionary without knowing
# a key using a list comprehension and a dict() constructor
 
# Initialising dictionary
test1 = {"akshat": 21, "nikhil": 22, "akash": 23, "manjeet": 27}
 
# Printing dictionary before removal
print("Original Dictionary : " + str(test1))
 
# Identify value to remove
item_to_remove = 23
 
# Create new dictionary without the item to remove
new_dict = dict((key, item)
                for key, item in test1.items() if item != item_to_remove)
 
# Printing dictionary after removal
print("Dictionary after remove is : " + str(new_dict))

Output
Original Dictionary : {'manjeet': 27, 'nikhil': 22, 'akshat': 21, 'akash': 23}
Dictionary after remove is : {'nikhil': 22, 'manjeet': 27, 'akshat': 21}

Time complexity: O(n), where n is the number of key-value pairs in the dictionary (since we iterate through all of them once).
Auxiliary space: O(n), as we create a new list of tuples that could potentially have n items. 

Method #6: Using the map() function.

Step-by-step approach:

Below is the implementation of the above approach:




# Python code to demonstrate how to remove
# an item from the dictionary without knowing
# a key using the map() function
 
# Define the function to remove the item
def remove_item(key_value_pair, item_to_remove):
    key, value = key_value_pair
    if value == item_to_remove:
        return None
    else:
        return (key, value)
 
# Initialising dictionary
test1 = {"akshat": 21, "nikhil": 22, "akash": 23, "manjeet": 27}
 
# Printing dictionary before removal
print("Original Dictionary : " + str(test1))
 
# Identify value to remove
item_to_remove = 23
 
# Use map() to apply remove_item() to each key-value pair in the dictionary
new_dict_map = map(lambda kv: remove_item(kv, item_to_remove), test1.items())
 
# Convert the resulting map object to a dictionary
new_dict = dict(filter(lambda x: x is not None, new_dict_map))
 
# Printing dictionary after removal
print("Dictionary after remove is : " + str(new_dict))

Output
Original Dictionary : {'akshat': 21, 'nikhil': 22, 'akash': 23, 'manjeet': 27}
Dictionary after remove is : {'akshat': 21, 'nikhil': 22, 'manjeet': 27}

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


Article Tags :