This is a Python Program to remove the given key from a dictionary.
The program takes a dictionary and removes a given key from the dictionary.
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.
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)
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.
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.
- Check Information Technology Books
- Apply for Python Internship
- Apply for Programming Internship
- Check Python Books
- Practice Programming MCQs