Python Program on Multiple Ways to remove a key from a dictionary

A dictionary in Python is a collection of key-value pairs. Sometimes, it becomes necessary to remove a specific key from the dictionary. Python provides multiple ways to remove a key from a dictionary and in this Python example we will discuss some of them in this blog post.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Using the del keyword

The easiest way to remove a key from a dictionary is by using the del keyword. The syntax is as follows:

Syntax:
del my_dict[key] 

my_dict is the name of the dictionary, 
key is the key that we want to remove.

Now let’s implement a program to delete a key using del keyword.

# create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# remove the key 'b'
del my_dict['b']

# print the updated dictionary
print(my_dict)
Output
{'a': 1, 'c': 3} 

2. Using the pop() method

The pop() method is another way to remove a key from a dictionary. The syntax is my_dict.pop(key)

# create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# remove the key 'b'
my_dict.pop('b')

# print the updated dictionary
print(my_dict)
Output
{'a': 1, 'c': 3} 

3. Using a dictionary comprehension

We can also use dictionary comprehension to remove a key from a dictionary. The syntax is as follows:

Syntax:
new_dict = {key: value for key, value in my_dict.items() if key != unwanted_key} 

my_dict is the name of the dictionary, 
unwanted_key is the key that we want to remove.
my_dict = {'a': 1, 'b': 2, 'c': 3}
new_dict = {key: value for key, value in my_dict.items() if key != 'b'}
print(new_dict)
Output
{'a': 1, 'c': 3} 

4. Conclusion

In this Python example, we discussed multiple ways to remove a key from a dictionary in Python. The del keyword and the pop() method are the most commonly used methods.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index