Table of Contents
In this example, you will learn to delete an element from a dictionary.
To understand this example, you should have the knowledge of the following Python programming topics:
- Python Dictionary
- Python del Statement
- Python Dictionary pop()
1. Example 1: Using del keyword
my_dict = {31: 'a', 21: 'b', 14: 'c'}
del my_dict[31]
print(my_dict)
Output
{21: 'b', 14: 'c'}
In the code above, the key:value pair with key as 31 is deleted using del keyword. del keyword gives a KeyError if the key is not present in the dictionary.
2. Example 2: Using pop()
my_dict = {31: 'a', 21: 'b', 14: 'c'}
print(my_dict.pop(31))
print(my_dict)
Output
a
{21: 'b', 14: 'c'}
Pass the key 31 as an argument to the pop() method. It deletes the key:value pair with key as 31 as shown in the output.
pop() also returns the value of the key passed.
Related posts:
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Remove Duplicate Element From a List
Python Global Keyword
Python time Module
Python Set isdisjoint()
Python @property decorator
Python Program to Find LCM
Python String zfill()
Python Statement, Indentation and Comments
Python next()
Python String title()
Python slice()
Python Operators
Python Program to Find Sum of Natural Numbers Using Recursion
Python Dictionary clear()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Program to Return Multiple Values From a Function
Python del Statement
Python String isdigit()
Python strftime()
Python Program to Convert Celsius To Fahrenheit
Python bytearray()
Python RegEx
Python String isspace()
Python sum()
Python Program to Check Armstrong Number
Python Program to Trim Whitespace From a String
Python Program to Find Hash of File
Python Program to Get a Substring of a String
Python datetime
Python Set pop()
Python super()