/  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. 

Example:

dict = {1: "One", 2: "Two" }
del dict[2]

line = "The dictionary after deletion is {}"
print(line.format(dict))

output:

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

Example:

dict = {1: "One", 2: "Two" }
deleted_value = dict.pop(2)

line = "The value removed from the dictionary of the key: 2 is {}"
print(line.format(deleted_value))

output:

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.  

Example:

dict = {1: "One", 2: "Two" }
deleted_value = dict.pop(3, None)

line = "The value removed from the dictionary of the key: 3 is {}"
print(line.format(deleted_value))

output:

 

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. 

Example:

dict = {1: "One", 2: "Two" }
new_dict = {k: v for k, v in dict.items() if k !=2}

line = "The new dictionary is {}"
print(line.format(new_dict))

output:

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.

Dictionary comprehension

 

Leave a comment