Python : Delete Key, Value from Dictionary

Using del keyword

Python provides del keyword to delete objects.
As dictionary stores < key : value > pairs, we can use del keyword to remove the key ( and its corresponding value ) from the dictionary.
Note: Before using the del keyword, check if the key exists in the dictionary. An exception is thrown if we try to delete the key that does not exist in the dictionary.


Below is the example python3 program that uses del keyword to delete the key from the dictionary.

academy = { "slap" : "Will", "slapped" : "Chris", "kiss" : "Jim", "kissed" : "alicia" }

print("Contents of academy : " + str(academy))

if "slap" in academy :
    del academy["slap"]
if "slapped" in academy :
    del academy["slapped"]

print("Contents of academy after deletion : " + str(academy))

Output

Contents of academy : {'slap': 'Will', 'slapped': 'Chris', 'kiss': 'Jim', 'kissed': 'alicia'}
Contents of academy after deletion : {'kiss': 'Jim', 'kissed': 'alicia'}

Using pop function

We pass a None to the pop function along with the key to be removed from the dictionary. By specifying the None keyword, the pop function does nothing if the key does not exist. The advantage of using the pop function for deleting the key from the dictionary is that if the key does not exist and we try to delete it using pop,
no exception is thrown.

Usage : < dict > . pop ( < key >, None )

Below is the example python3 program that uses pop function to delete the key from the dictionary.

dict_ = { "broken_leg" : "push", "prime" : "amazon", "bang" : "she", "sold" : "gold", "anti_vaxxer" : "joker", "string" : "g" }

print("Contents of dict_ : " + str(dict_))

dict_.pop("broken_leg", None)
dict_.pop("sold", None)
dict_.pop("sold", None)

print("Contents of dict_ after deletion : " + str(dict_))

Output

Contents of dict_ : {'broken_leg': 'push', 'prime': 'amazon', 'bang': 'she', 'sold': 'gold', 'anti_vaxxer': 'joker', 'string': 'g'}
Contents of dict_ after deletion : {'prime': 'amazon', 'bang': 'she', 'anti_vaxxer': 'joker', 'string': 'g'}


Copyright (c) 2019-2022, Algotree.org.
All rights reserved.