Python Program to Remove Given Key from a Dictionary

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)
Python Program to Remove Given Key from a Dictionary 1

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)

Remove Python 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 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)

Delete Python 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'}
>>>