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 Print Output Without a Newline
Python Errors and Built-in Exceptions
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python help()
Python Program to Remove Duplicate Element From a List
Python Program to Sort Words in Alphabetic Order
Python String isalnum()
Python Program to Compute all the Permutation of the String
Python Package
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Measure the Elapsed Time in Python
Python Program to Multiply Two Matrices
Python Tuple count()
Python Anonymous / Lambda Function
Python String rindex()
Python String isspace()
Python Program to Make a Flattened List from Nested List
Python repr()
Python Set union()
Python Program to Count the Number of Digits Present In a Number
Python List insert()
Python Set issuperset()
Python String lower()
Python Input, Output and Import
Python String count()
Python String rsplit()
Python dir()
Python List Comprehension
Python Functions
Python Program to Iterate Through Two Lists in Parallel
How to Get Started With Python?
Python String startswith()