by BehindJava

Write a program to Remove the Given Key from a Dictionary in Python

Home » python » Write a program to Remove the Given Key from a Dictionary in Python

In this tutorial we are going to learn about removing the Given Key from a Dictionary in Python.

Python Program to Remove the Given Key from a Dictionary

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)

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.