Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
Dictionary is a collection in python which is used to store data as Key:value pair.
Example:
dict = { "python" : 1, "C++" : 3, "javaScript" : 2 }
Remove a key from a dictionary in python
We have a dictionary data structure and we will take input from the user on the keys to be removed from it. We need to write a program to delete this key from the dictionary and print the updated dictionary.
We need to find the key and remove it. This can be done in python using multiple methods provided on collections. Let’s see them at work.
Input:
dict = { "python" : 1, "C++" : 3, "javaScript" : 2 } python
Output:
updated dictionary : { "C++" : 3, "javaScript" : 2 }
Method 1: Using pop() method on dictionary
To remove any key from python we can use the pop() method.
The pop() method on a dictionary is used to delete a key:value pair. The method returns the removed pair and if it does not exist it prints the string which we can give as an extra argument (otherwise throws an exception).
Syntax:
Program to remove a key from dictionary using pop() method in Python
Output:
Method 2: Using del
Another method that can be used to delete a key from a dictionary is using the del. We can use the del keyword followed by the dict[key] notation to remove the specific key from the dictionary.
del does not accept any extra value to be returned in case of false value. It will instead return an error.
Program to remove key from dictionary using del
Output:
Method 3: By creating a new dictionary using comprehension
We will filter off the key:val while creating a new dictionary using comprehension in Python.
Program to remove a key from dictionary using comprehension
Output:
Explanation:
In the above code, we have deleted a key from the dictionary using comprehension. Comprehension is a built-in feature that allows the programmer to perform the task in a lesser number of lines of code.
need an explanation for this answer? contact us directly to get an explanation for this answerWith comprehension, we have filtered off the key which we want to delete from the dictionary. For this, we loop on easy items of the dictionary and add them to a new dictionary if the key is not equal to the key to be deleted.