Write a Python Program to Remove Given Key from a Dictionary with a practical example.
Python Program to Remove Given Key from a Dictionary Example 1
In this python program, we are using if statement to check whether the key exists in this Dictionary or not. Inside the If, there is a del function to delete key-value from this dictionary.
# Python Program to Remove Given Key from a Dictionary myDict = {'name': 'John', 'age': 25, 'job': 'Developer'} print("Dictionary Items : ", myDict) key = input("Please enter the key that you want to Delete : ") if key in myDict: del myDict[key] else: print("Given Key is Not in this Dictionary") print("\nUpdated Dictionary = ", myDict)
OUTPUT
Python Program to Delete Given Key from a Dictionary Example 2
This Python program is another approach to delete Key Value from a dictionary. Here, we are using keys functions to find a key inside a dictionary.
# Python Program to Remove Given Key from a Dictionary myDict = {'name': 'John', 'age': 25, 'job': 'Developer'} print("Dictionary Items : ", myDict) key = input("Please enter the key that you want to Delete : ") if key in myDict.keys(): del myDict[key] else: print("Given Key is Not in this Dictionary") print("\nUpdated Dictionary = ", myDict)
OUTPUT
Python Program to Delete Given Key from a Dictionary Example 3
In this python program, we are using the pop function to remove the key from a dictionary.
# Python Program to Remove Given Key from a Dictionary myDict = {'name': 'John', 'age': 25, 'job': 'Developer'} print("Dictionary Items : ", myDict) key = input("Please enter the key that you want to Delete : ") if key in myDict.keys(): print("Removed Item : ", myDict.pop(key)) else: print("Given Key is Not in this Dictionary") print("\nUpdated Dictionary = ", myDict)
OUTPUT