Python

Python – How to remove key from dictionary ?

In this tutorial, we will see how to remove key from dictionary in python.

How to remove key from dictionary?

dict.pop() function is used to remove the key from a dictionary.

def remove_key(my_dict,key):
    my_dict.pop(key, None)

if __name__ == '__main__':
    fruits = {
        1:'apple',
        2:'grape',
        3:'orange'
    }
    remove_key(fruits,2)
    print(fruits)

Output:

{1: 'apple', 3: 'orange'}

The del keyword can also be used to delete key from dictionary.

def remove_key_del(my_dict,key):
    try:
       del my_dict[key]
    except KeyError:
        pass

if __name__ == '__main__':
    fruits = {
        1:'apple',
        2:'grape',
        3:'orange'
    }
    remove_key_del(fruits,3)
    print(fruits)

Output:

{1: 'apple', 2: 'grape'}

I always recommend you to keep the del expression in try expect block, as it raises KeyError if the given key does not exist in the dictionary.

Happy Learning :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Python

Python Dictionary Methods and Usages

Hi everyone, In this tutorial, we will learn about Python dictionary usages and its methods using examples. 1. What is a Python Dictionary? Dictionary in Python is a…

Ask a question or leave a comment