Python Remove Key from a Dictionary: A Complete Guide

Posted in /  

Python Remove Key from a Dictionary: A Complete Guide
vinaykhatri

Vinay Khatri
Last updated on May 30, 2024

    Python dictionary store its elements in the format of key:value pairs separated with commas. And if we remove the key from a dictionary, it will also remove the corresponding key value. Dictionaries are mutable data structures which means we can remove any key-value pair from a dictionary when we do not require it any longer. There are two ways to remove a specific key from a dictionary, the pop(key) method and the del keyword.

    In this Python tutorial, we will discuss these two specific ways to delete or remove a key from a dictionary.

    Remove a Key from a Dictionary using the dictionary pop() method

    Similar to the Python list, the dictionary also provides pop() method to remove a key-value pair from a dictionary object. But unlike Python list, the dictionary's pop() method requires a specific key name as an argument that we want to remove from the dictionary.

    syntax

    dictionary_name.pop(key, default)

    The dictionary pop method can accept two argument values.

    1. key (mandatory): It is the key name that we want to remove from the dictionary. And if we specify the wrong key name to the pop() method and does not specify the default argument, it will return the KeyError .
    2. default (optional): It is an optional argument value, that represents the return value if the key does not exist in the dictionary. If we do not specify it and the key is invalid, the pop method will return the KeyError

    Example 1 (remove a valid key)

    student1 = {'Name': 'Rahul', 'Age':23, 'Gender':'Male', 'Unknown':'NoData'}
    
    # the key to remove from the dictionary
    key = 'Unknown'
    
    # remove the key from the dictionary
    print("Removed: ",student1.pop(key))
    
    print(student1)

    Output

    Removed: NoData
    {'Name': 'Rahul', 'Age': 23, 'Gender': 'Male'}

    Example 2 (KeyError with pop()) If we specify a key in the pop method that does not exist, the method will return the KeyError.

    student1 = {'Name': 'Rahul', 'Age':23, 'Gender':'Male', 'Unknown':'NoData'}
    
    # the key to remove from the dictionary
    key = 'Height'
    
    # remove the key from the dictionary
    print("Removed: ",student1.pop(key))
    
    print(student1)

    Output

    Traceback (most recent call last):
      File "main.py", line 7, in 
        print("Removed: ",student1.pop(key))
    KeyError: 'Height'

    Example 3 (pop default argument) It's always a good practice to specify the default argument to the dictionary pop method because it protects the program from KeyError in case of an invalid key.

    student1 = {'Name': 'Rahul', 'Age':23, 'Gender':'Male', 'Unknown':'NoData'}
    
    # the key to remove from the dictionary
    key = 'Height'
    
    # remove the key from the dictionary
    print("Removed: ",student1.pop(key, "!No Key Removed(Key is not in dictionary)"))
    
    print(student1)

    Output

    Removed: !No Key Removed(Key is not in dictionary)
    {'Name': 'Rahul', 'Age': 23, 'Gender': 'Male', 'Unknown': 'NoData'}

    Remove a Key from a Dictionary using Python del keyword

    The Python del keyword stands for delete, and it can delete any object value from the program. We can use the del keyword on a dictionary key:value pair and delete them.

    Syntax

    del dictionary_name[key]

    Example 1 (remove key using del)

    student1 = {'Name': 'Rahul', 'Age':23, 'Gender':'Male', 'Unknown':'NoData'}
    
    # the key to remove from the dictionary
    key = 'Unknown'
    
    # remove the key from the dictionary
    del student1[key]
    
    print(student1)

    Output

    {'Name': 'Rahul', 'Age': 23, 'Gender': 'Male'}
    

    Example 2 (key Error with del) If we specify an invalid key that does not exist in the dictionary, we will receive the KeyError.

    student1 = {'Name': 'Rahul', 'Age':23, 'Gender':'Male', 'Unknown':'NoData'}
    
    # the key to remove from the dictionary 
    key = 'Height'    #invalid key
    
    # remove the key from the dictionary
    del student1[key]
    
    print(student1)

    Output

    Traceback (most recent call last):
        File "main.py", line 7, in <module>
            del student1[key]
    KeyError: 'Height'

    To handle this error, we can use Python try..except error handling.

    Bonus: Remove dictionary key values with the popitem() method

    Dictionary also provides the popitem() method to remove or delete a key-value pair from the dictionary. But unlike the pop() method, we can not specify any specific key to remove using this method. With the popitem() method, we can only remove the last key-value pair from the dictionary.

    Syntax

    dict_name.popitem()

    As the popitem() does not accept any argument value, this leaves no place to remove any specific key value. The popitem() method removes the last key-value pair and return them as a tuple pair.

    Example

    student1 = {'Name': 'Rahul', 'Age':23, 'Gender':'Male', 'Unknown':'NoData'}
    
    # remove the last key:value pair
    print("Removed: ",student1.popitem())
    
    print(student1)

    Output

    Removed: ('Unknown', 'NoData')
    {'Name': 'Rahul', 'Age': 23, 'Gender': 'Male'}

    Wrapping Up!

    To remove a specific key from a Python dictionary, we can either use the dictionary pop() method or Python del keyword. The pop() method provide a better and efficient way to remove a dictionary key because in the pop() method we can also specify the default value if the key is invalid. But with the del keyword we have to face the KeyError in case of invalid keys. We also have the popitem() method for dictionary objects if we wish to remove the last key:value pair.

    People are also reading:

    Leave a Comment on this Post

    0 Comments