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 Program to Randomly Select an Element From the List
Python Set discard()
Python Program to Convert Two Lists Into a Dictionary
Python Program to Display Calendar
Python round()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python bytearray()
Python Directory and Files Management
Python *args and **kwargs
Python String split()
Python object()
Python String expandtabs()
Python String lstrip()
Python Set symmetric_difference_update()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python String find()
Python Set copy()
Python Program to Differentiate Between type() and isinstance()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python List copy()
Python Program to Trim Whitespace From a String
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Count the Number of Occurrence of a Character in String
Python String isdigit()
Python Program to Display the multiplication Table
Python hasattr()
Python Set issubset()
Deep Learning in Python - LazyProgrammer
Python Function Arguments
Python datetime
Python Operator Overloading
Python Program to Add Two Matrices