Python Program to Remove a Key from a Dictionary

This is a Python Program to remove the given key from a dictionary.

Problem Description

The program takes a dictionary and removes a given key from the dictionary.

Problem Solution

1. Declare and initialize a dictionary to have some key-value pairs.
2. Take a key from the user and store it in a variable.
3. Using an if statement and the in operator, check if the key is present in the dictionary.
4. If it is present, delete the key-value pair.
5. If it isn’t present, print that the key isn’t found and exit the program.
6. Exit.

Program/Source Code

Here is source code of the Python Program to remove the given key from a dictionary. The program output is also shown below.

d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
print(d)
key=raw_input("Enter the key to delete(a-d):")
if key in d: 
    del d[key]
else:
    print("Key not found!")
    exit(0)
print("Updated dictionary")
print(d)
Program Explanation

1. User must enter the key to be checked and store it in a variable.
2. An if statement and the in operator is used check if the key is present in the dictionary.
3. If it is present, the key-value pair is deleted.
4. If it isn’t present, “Key not found!” is printed and the program is exited.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):c
Updated dictionary
{'a': 1, 'b': 2, 'd': 4}
 
Case 2:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):g
Key not found!

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.