How to Remove the Given Key from a Dictionary in Python


This example will teach us how to deletes the key specified in a dictionary.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

dict1 = {'A': 11, 'B': 22, 'C': 33, 'D': 44, 'E': 55}
print("The original dictionary is: ", dict1)
delKey = input("Please input the key to be deleted (A-E):")
if delKey in dict1.keys():
    del dict1[delKey]
else:
    print("The key does not exist!")
    exit(0)
print("The dictionary after deleting: ", dict1)

Output:

Case 1:
The original dictionary is: {'E': 55, 'C': 33, 'B': 22, 'A': 11, 'D': 44}
Please input the key to be deleted (A-E):E
The dictionary after deleting: {'C': 33, 'B': 22, 'A': 11, 'D': 44}

Case 2:
The original dictionary is: {'A': 11, 'B': 22, 'E': 55, 'D': 44, 'C': 33}
Please input the key to be deleted (A-E):G
The key does not exist!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments