Tuesday, 21 January 2025

Day 95 : Python Program to Remove a Key from a Dictionary

 


def remove_key_from_dict(dictionary, key_to_remove):

    """

    Removes a key from the dictionary if it exists.

    Args:

        dictionary (dict): The dictionary to modify.

        key_to_remove: The key to be removed from the dictionary.

     Returns:

        dict: The modified dictionary.

    """

    if key_to_remove in dictionary:

        del dictionary[key_to_remove]

        print(f"Key '{key_to_remove}' has been removed.")

    else:

        print(f"Key '{key_to_remove}' not found in the dictionary.")

    return dictionary

my_dict = {"name": "Max", "age": 25, "city": "UK"}

print("Original Dictionary:", my_dict)

key = input("Enter the key to remove: ")

updated_dict = remove_key_from_dict(my_dict, key)

print("Updated Dictionary:", updated_dict)

#source code --> clcoding.com 

Code Explanation:

Function Definition
def remove_key_from_dict(dictionary, key_to_remove):
    """
    Removes a key from the dictionary if it exists.

    Args:
        dictionary (dict): The dictionary to modify.
        key_to_remove: The key to be removed from the dictionary.

    Returns:
        dict: The modified dictionary.
    """
Purpose: This function is created to remove a specific key from a dictionary, if the key exists.
Parameters:
dictionary: The dictionary that you want to modify.
key_to_remove: The key that you wish to remove from the dictionary.
Returns: The modified dictionary after attempting to remove the key.

Check if Key Exists
if key_to_remove in dictionary:
    del dictionary[key_to_remove]
    print(f"Key '{key_to_remove}' has been removed.")
else:
    print(f"Key '{key_to_remove}' not found in the dictionary.")
if key_to_remove in dictionary: Checks whether the key exists in the dictionary.
del dictionary[key_to_remove]: If the key exists, it deletes the key-value pair from the dictionary.

Print Statement:
If the key is found and removed, a success message is displayed.
If the key is not found, an error message is displayed.

Return Modified Dictionary
return dictionary
The function returns the updated dictionary, whether or not any changes were made.

Dictionary Creation
my_dict = {"name": "Max", "age": 25, "city": "UK"}
print("Original Dictionary:", my_dict)
A dictionary named my_dict is defined with three key-value pairs: "name": "Max", "age": 25, and "city": "UK".
The original dictionary is printed to show its content before any modifications.

User Input
key = input("Enter the key to remove: ")
Prompts the user to enter the name of the key they want to remove from the dictionary.

Function Call
updated_dict = remove_key_from_dict(my_dict, key)
Calls the remove_key_from_dict function, passing the dictionary my_dict and the user-provided key as arguments.
The function processes the request and returns the updated dictionary.

Print Updated Dictionary
print("Updated Dictionary:", updated_dict)
Displays the dictionary after attempting to remove the specified key, allowing the user to see the changes made.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (91) AI (37) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (184) C (77) C# (12) C++ (83) Course (67) Coursera (234) Cybersecurity (24) Data Analytics (2) data management (11) Data Science (135) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Euron (22) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Generative AI (5) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Java quiz (1) Leet Code (4) Machine Learning (65) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (961) Python Coding Challenge (406) Python Quiz (58) Python Tips (3) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses