Python | Remove item from dictionary when key is unknown
Last Updated :
27 Apr, 2023
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.
Python3
test1 = {"akshat" : 21 , "nikhil" : 22 , "akash" : 23 , "manjeet" : 27 }
print ("Original Dictionary : " + str (test1))
item_to_remove = 23
for key, item in test1.items():
if item is item_to_remove:
del test1[key]
break
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.
Python3
test1 = {"akshat" : 21 , "nikhil" : 22 , "akash" : 23 , "manjeet" : 27 }
print ("Original Dictionary : " + str (test1))
value_to_remove = 23
res = {key: value for key, value in test1.items()
if value is not value_to_remove}
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.
Python3
test1 = {"akshat" : 21 , "nikhil" : 22 , "akash" : 23 , "manjeet" : 27 }
print ("Original dictionary : " + str (test1))
value_to_remove = 23
for key in test1.keys():
if test1[key] = = value_to_remove:
test1.pop(key)
break
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:
Python3
test1 = { "akshat" : 21 , "nikhil" : 22 , "akash" : 23 , "manjeet" : 27 }
value_to_remove = 23
filtered_dict = dict ( filter ( lambda item: item[ 1 ] ! = value_to_remove, test1.items()))
print (filtered_dict)
|
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:
- Initialize the dictionary.
- Identify the value that needs to be removed and save it to a variable.
- Create a list of tuples containing all key-value pairs from the original dictionary except the one with the value to be removed.
- Use the dict() constructor with the list of tuples to create a new dictionary.
- Print the new dictionary.
Below is the implementation of the above approach:
Python
test1 = { "akshat" : 21 , "nikhil" : 22 , "akash" : 23 , "manjeet" : 27 }
print ( "Original Dictionary : " + str (test1))
item_to_remove = 23
new_dict = dict ((key, item)
for key, item in test1.items() if item ! = item_to_remove)
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:
- Define a function remove_item() that takes a dictionary and an item_to_remove as input parameters.
- Use the map() function to apply the remove_item() function to each key-value pair in the dictionary.
- The remove_item() function returns None for the key-value pair with the item_to_remove value, so the resulting map object will only contain the other key-value pairs.
- Convert the map object to a dictionary using the dict() constructor.
- Return the new_dict.
Below is the implementation of the above approach:
Python3
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)
test1 = { "akshat" : 21 , "nikhil" : 22 , "akash" : 23 , "manjeet" : 27 }
print ( "Original Dictionary : " + str (test1))
item_to_remove = 23
new_dict_map = map ( lambda kv: remove_item(kv, item_to_remove), test1.items())
new_dict = dict ( filter ( lambda x: x is not None , new_dict_map))
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.
Please Login to comment...