How to delete a key from a python dictionary

Python program to delete a key from a dictionary :

In this tutorial, we will learn how to delete a key from a dictionary using python 3.The dictionary is given. We will ask the user to enter a key value that need to be deleted. The program will check if any member with that user input key exist or not. If exist, it will delete that value . If not it will print one message to the user to inform. Let’s take a look at the program first :

Python 3 program to delete a dictionary key :

#1
dict = {'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10}

#2
print("Current Dictionary : ",dict)

#3
key_to_delete = input("Enter the key to delete : ")

#4
if key_to_delete in dict:
	del dict[key_to_delete]
else :
	print("Please enter a valid key.")

#5
print("Final Dictionary ",dict)

Explanation :

The commented numbers in the above program denote the step number below :

1. dict is the given dictionary with different key-value pairs.
2. Print the dictionary to the user.
3. Ask the user to enter a key value that need to be deleted. Store the value in variable key_to_delete.
4. Check if the key exist in the dict or not. If yes, delete the key-value pair using del dict[key] method. Else, ask the user to enter a valid key.
5. Finally, print out the dictionary again to the user.

Sample Examples :

Current Dictionary :  {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10}
Enter the key to delete : two
Final Dictionary  {'one': 1, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10}

Current Dictionary :  {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10}
Enter the key to delete : eleven
Please enter a valid key.
Final Dictionary  {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10}

Leave a Reply