Remove Key from Dictionary PythonWe know that the elements in the dictionary are comprised of key-value pairs. With the help of these keys, the corresponding values can be easily fetched. In this article, we will learn how we can remove the key from the dictionary in Python. We will use the following methods to do the same-
So, let's get started with the first one! Using del()The following program shows how we can remove a key from dictionary using del(). Output: The values present in the dictionary are: {'English': 129901, 'Mathematics': 129902, 'Physics': 129903, 'Chemistry': 129904, 'Computer Science': 129905} The values present in the dictionary after removal are: {'English': 129901, 'Mathematics': 129902, 'Physics': 129903, 'Computer Science': 129905} Explanation- Let's understand what we have done in the above program-
Now, in the second program, we will learn how pop() can be used. Using pop()Consider the program given below, Output: The values present in the dictionary are: {'English': 129901, 'Mathematics': 129902, 'Physics': 129903, 'Chemistry': 129904, 'Computer Science': 129905} The value of the removed key: 129902 The values present in the dictionary after removal are: {'English': 129901, 'Physics': 129903, 'Chemistry': 129904, 'Computer Science': 129905} Explanation- It's time to have a look at the explanation of this program,
Now, let's see how dictionary comprehension can help us with this, Using items() and Dictionary ComprehensionThe program given below demonstrates how it can be done, Output: The values present in the dictionary are: {'English': 129901, 'Mathematics': 129902, 'Physics': 129903, 'Chemistry': 129904, 'Computer Science': 129905} The values present in the dictionary after removal are: {'Mathematics': 129902, 'Physics': 129903, 'Chemistry': 129904, 'Computer Science': 129905} Explanation- Let's check what happened here,
Finally, in the last program, we will see how a loop can be used to remove multiple keys from a dictionary. Using loop to Remove Multiple KeysThe following illustrates the same- Output: The dictionary after removal of keys is: {'Mathematics': 129902, 'Chemistry': 129904, 'Computer Science': 129905} Explanation- Let's understand what we have done in the above program-
ConclusionIn this article, we came across another interesting task based on dictionaries and learned the different ways of removing keys from it in Python.
Next TopicSwap Elements in list of Python
|