How to Remove a Key From a Dictionary in Python?

Spread the love

Problem –

You want to remove a key from a dictionary in python.

Solution –

Let’s create a dictionary first.

In [1]: person = {'Name': 'Noah', 'Age': 25, 'Location': 'New York', 'Profession': 'Student'}

Now if I want to delete the Profession key, I can simple use the del keyword.

In [2]: del person['Profession']

In [3]: person
Out[3]: {'Name': 'Noah', 'Age': 25, 'Location': 'New York'}

This method will raise a keyError if key is not present in the dictionary.

You can also delete a key using the pop method.

In [4]: loc = person.pop('Location', None)

In [5]: loc
Out[5]: 'New York'

In [6]: person
Out[6]: {'Name': 'Noah', 'Age': 25}

The pop method delete the key from the dictionary and return it. If the key is not present then it will return None. If you don’t specify None and key is not present then python will raise a KeyError.

Rating: 1 out of 5.

Leave a Reply