Python Remove Key from Dictionary if Exists
Last Updated :
13 Feb, 2024
Dictionaries in Python are versatile data structures that allow you to store and manipulate key-value pairs. At times, you may need to remove a key from a dictionary if it exists. In this article, we will explore three different methods to achieve this task: using the pop()
method, using the del
statement, and employing dictionary comprehension.
Python Remove Key from Dictionary if Exists
Below, are the methods in Python Remove Key from Dictionary if Exists.
Python Remove Key from Dictionary if Exists Using pop() Method
The pop()
method is a built-in function in Python that allows you to remove an item from a dictionary based on its key. In this example, the pop()
method is used with the key ‘geek’. If the key exists, it will be removed from the dictionary, and its corresponding value will be stored in the variable removed_value
.
Python3
my_dict = { 'gfg' : 3 , 'geeks' : 5 , 'for' : 2 , 'geek' : 4 , 'tutorial' : 8 }
key_to_remove = 'geek'
removed_value = my_dict.pop(key_to_remove, None )
print (f "Dictionary after removing key '{key_to_remove}': {my_dict}" )
print (f "Removed value: {removed_value}" )
|
Output
Dictionary after removing key 'geek': {'gfg': 3, 'geeks': 5, 'for': 2, 'tutorial': 8}
Removed value: 4
Python Remove Key from Dictionary if Exists Using del Method
The del
statement is a general-purpose way to remove items in Python, including dictionary keys. Here, the del
statement is employed to remove the key ‘geek’ from the dictionary. The code includes a check to ensure that the key exists in the dictionary before attempting removal.
Python3
my_dict = { 'gfg' : 3 , 'geeks' : 5 , 'for' : 2 , 'geek' : 4 , 'tutorial' : 8 }
key_to_remove = 'geek'
if key_to_remove in my_dict:
del my_dict[key_to_remove]
print (f "Key '{key_to_remove}' removed. Dictionary after removal: {my_dict}" )
else :
print (f "Key '{key_to_remove}' not found in the dictionary." )
|
Output
Key 'geek' removed. Dictionary after removal: {'gfg': 3, 'geeks': 5, 'for': 2, 'tutorial': 8}
Python Remove Key from Dictionary if Exists Using dictionary comprehension
Another concise way to remove a key from a dictionary is by using dictionary comprehension. This method creates a new dictionary by excluding the specified key-value pair. In this example, a new dictionary is created by iterating through the key-value pairs of the original dictionary and excluding the specified key (‘geek’).
Python3
my_dict = { 'gfg' : 3 , 'geeks' : 5 , 'for' : 2 , 'geek' : 4 , 'tutorial' : 8 }
key_to_remove = 'geek'
my_dict = {k: v for k, v in my_dict.items() if k ! = key_to_remove}
print (f "Dictionary after removing key '{key_to_remove}': {my_dict}" )
|
Output
Dictionary after removing key 'geek': {'gfg': 3, 'geeks': 5, 'for': 2, 'tutorial': 8}
Share your thoughts in the comments
Please Login to comment...