Get The Most Affordable Hosting in the World!
Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.
Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!
Get Started Now!Using del Keyword
Python's del keyword deletes any object from the memory. Here we use it to delete a key-value pair in a dictionary.
Syntax
Example
It will produce the following output −
numbers dictionary before delete operation: {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'} numbers dictionary before delete operation: {10: 'Ten', 30: 'Thirty', 40: 'Forty'}
Example
The del keyword with the dict object itself removes it from memory.
It will produce the following output −
numbers dictionary before delete operation: {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'} Traceback (most recent call last): File "C:\Users\mlath\examples\main.py", line 5, in <module> print ("numbers dictionary before delete operation: \n", numbers) ^^^^^^^ NameError: name 'numbers' is not defined
Using pop() Method
The pop() method of dict class causes an element with the specified key to be removed from the dictionary.
Syntax
Return value
The pop() method returns the value of the specified key after removing the key-value pair.
Example
It will produce the following output −
numbers dictionary before pop operation: {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'} nubvers dictionary after pop operation: {10: 'Ten', 30: 'Thirty', 40: 'Forty'} Value popped: Twenty
Using popitem() Method
The popitem() method in dict() class doesn't take any argument. It pops out the last inserted key-value pair, and returns the same as a tuple
Syntax
Return Value
The popitem() method return a tuple contain key and value of the removed item from the dictionary
Example
It will produce the following output −
numbers dictionary before pop operation: {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'} numbers dictionary after pop operation: {10: 'Ten', 20: 'Twenty', 30: 'Thirty'} Value popped: (40, 'Forty')
Using clear() Method
The clear() method in dict class removes all the elements from the dictionary object and returns an empty object.
Syntax
Example
It will produce the following output −
numbers dictionary before clear method: {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'} numbers dictionary after clear method: {}
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.