Open In App

Python | Remove item from dictionary when key is unknown

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

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




# 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. 

Python3




# 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. 

Python3




# 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:

Python3




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:

  • 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




# 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:

  • 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




# 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.



Previous Article
Next Article

Similar Reads

Python Remove Item from Dictionary by Key
A dictionary in Python is a mutable and dynamic data type that provides a flexible way to access and manipulate data. As distinct from a list or a tuple, where elements are accessed via indices, a dictionary leverages a unique key representing each item. In this article, we will see how to remove items from the dictionary by key in Python. Remove I
3 min read
Python - Add item after given Key in dictionary
Given a dictionary and a Key, add new item after a particular key in dictionary. Input : test_dict = {"Gfg" : 3, "is" : 5, "for" : 8, "Geeks" : 10}, K = "is", add_item = {"good" : 19} Output : {'Gfg': 3, 'is': 5, 'good': 19, 'for': 8, 'Geeks': 10} Explanation : Item added after desired key in dictionary. Input : test_dict = {"Gfg" : 3, "is" : 5, "f
4 min read
Delete a Python Dictionary Item If the Key Exists
In Python, dictionaries are like containers that help us keep and find information easily. They use key-value pairs to organize data, making them super helpful. But sometimes, we need to get rid of something specific from the dictionary, like when we know the key. This article explores some simple ways to do that efficiently How To Delete A Diction
3 min read
Python Remove Item from Dictionary by Value
Python, with its elegant syntax and powerful data structures, stands out as one of the most favored programming languages. Among its arsenal of data structures, the dictionary is a versatile and indispensable tool for developers. Dictionaries facilitate the storage of key-value pairs, allowing for efficient data retrieval and manipulation. In this
3 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Unknown facts about Python
Python is a widely-used general-purpose, high-level programming language. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently. Here are some interesting facts about py
4 min read
Detect an Unknown Language using Python
The idea behind language detection is based on the detection of the character among the expression and words in the text. The main principle is to detect commonly used words like to, of in English. Python provides various modules for language detection. In this article, the modules covered are: langdetecttextbloblangid Method 1: Using langdetect li
2 min read
Find the average of an unknown number of inputs in Python
Prerequisites: *args and **kwargs in Python The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyword, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the wo
3 min read
Convert "unknown format" strings to datetime objects in Python
In this article, we are going to see how to convert the "Unknown Format" string to the DateTime object in Python. Suppose, there are two strings containing dates in an unknown format and that format we don't know. Here all we know is that both strings contain valid date-time expressions. By using the dateutil module containing a date parser that ca
3 min read
three90RightbarBannerImg