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 Set issuperset()
Python print()
Python Program to Catch Multiple Exceptions in One Line
Python String casefold()
Python all()
Python String rfind()
Python Dictionary update()
Python property()
Python Inheritance
Python if...else Statement
Python Program to Sort Words in Alphabetic Order
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Merge Two Dictionaries
Python exec()
Python List
Python Set isdisjoint()
Python String lstrip()
Python eval()
Python String format_map()
Python Program to Get File Creation and Modification Date
Intelligent Projects Using Python - Santanu Pattanayak
Python Set symmetric_difference_update()
Python String endswith()
Python Shallow Copy and Deep Copy
Python dir()
Python String zfill()
Python Program to Access Index of a List Using for Loop
Python String isprintable()
Python String replace()
Python Program to Trim Whitespace From a String
Python Program to Find Numbers Divisible by Another Number
Python hasattr()