/  Technology   /  How can I remove a key from a Python dictionary?

How can I remove a key from a Python dictionary?

How can I remove a key from a Python dictionary?

 

Dictionary is an unordered collection of data in the form of key-value pairs separated by commas inside curly brackets. Dictionaries are indexed by keys. They are generally optimized to retrieve values when the key is known. Values (definitions) are mapped to a specific key (words) similar to that of a dictionary in the real world. 

Now in this article, we will discuss different ways using which we can remove a key from a given dictionary.

They are:

  • Using del
  • Using pop()
  • Using dictionary comprehension

 

Using del keyword:

This keyword performs in-place deletion of a key-value pair from a dictionary. 

This method raises an exception if the specified key isn’t present in the dictionary. So if the key doesn’t exist, the exception needs to be handled.

Using pop():

This method also performs in-place deletion of a key-value pair and in addition, also returns the deleted value

This method raises KeyError if the specified key isn’t present in the dictionary. The good part of using this method is that we can handle this exception. There is an optional parameter that we can pass to this method and it will return this value when a key isn’t found in the dictionary. 

Using dictionary comprehension:

 

The above-discussed methods do in-place deletion of key-value pairs which means it destroys the reference of this key-value pair. When we use dictionary comprehension, no in-place deletion is done but a new dictionary is created on a condition that excludes our key-value pair. 

Note: This method increases memory usage as it’s creating a new dictionary every time we use it.

To learn more about dictionary comprehension refer to the article below.

https://www.i2tutorials.com/dbms-introduction/dbms-dictionary-comprehension-in-python/

 

Leave a comment