Write a Python Program to Remove a Given Key from a Dictionary using the if else statement, del, keys, and pop functions with a practical example.
Python Program to Remove Given Key from a Dictionary using if else
In this program, we are using the 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.
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)
Python Program to Delete Given Key from a Dictionary using del function
This Python program is another approach to deleting Key values from a dictionary. Here, we are using keys functions to find a key inside 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)
Remove dictionary key output
Dictionary Items : {'name': 'John', 'age': 25, 'job': 'Developer'}
Please enter the key that you want to Delete : name
Updated Dictionary = {'age': 25, 'job': 'Developer'}
Python Program to Delete Given Key from a Dictionary using pop
In this program, we are using the pop function to remove the 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)
Delete dictionary key output
Dictionary Items : {'name': 'John', 'age': 25, 'job': 'Developer'}
Please enter the key that you want to Delete : age
Removed Item : 25
Updated Dictionary = {'name': 'John', 'job': 'Developer'}
>>>
Dictionary Items : {'name': 'John', 'age': 25, 'job': 'Developer'}
Please enter the key that you want to Delete : sal
Given Key is Not in this Dictionary
Updated Dictionary = {'name': 'John', 'age': 25, 'job': 'Developer'}
>>>