HomePythonPython Program to Remove a Key from a Dictionary

Python Program to Remove a Key from a Dictionary

This program demonstrates how to remove a key from a dictionary in Python.

Problem Statement:

Given a dictionary, remove a specific key and its corresponding value from the dictionary in python.

Python Program to Remove a Key from a Dictionary

def remove_key(dictionary, key_to_remove):
    if key_to_remove in dictionary:
        del dictionary[key_to_remove]
        print(f"Key '{key_to_remove}' and its value removed from the dictionary.")
    else:
        print(f"Key '{key_to_remove}' not found in the dictionary.")

# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Key to remove
key_to_remove = 'b'

remove_key(my_dict, key_to_remove)

print("Updated Dictionary:", my_dict)

How It Works:

  1. The program defines a function remove_key which takes a dictionary and a key as arguments.
  2. Inside the function, it checks if the given key exists in the dictionary using the in operator.
  3. If the key exists, it uses the del statement to remove the key-value pair from the dictionary.
  4. If the key is not found, it prints a message indicating that the key was not found.
  5. The program then creates an example dictionary my_dict and specifies a key key_to_remove that needs to be removed.
  6. The remove_key function is called with the my_dict and key_to_remove as arguments.
  7. Finally, the updated dictionary is printed.

Input/Output:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...