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 strftime()
Python format()
Python Program to Iterate Over Dictionaries Using for Loop
Python List insert()
Python List pop()
Python Program to Check if a Key is Already Present in a Dictionary
Python File I/O Operation
Python Set isdisjoint()
Python if...else Statement
Python Program to Parse a String to a Float or Int
Python globals()
Deep Learning with Python - Francois Cholletf
Python Program to Find Numbers Divisible by Another Number
Python Program to Convert Bytes to a String
Python Program to Check Armstrong Number
Python iter()
Python Program to Check Prime Number
Python Program to Concatenate Two Lists
Python memoryview()
Python String join()
Python Program to Get File Creation and Modification Date
Python Program to Safely Create a Nested Directory
Python Program to Find Armstrong Number in an Interval
Python Closures
Python divmod()
Python List
Python String center()
Python Program to Trim Whitespace From a String
Python int()
Python frozenset()
Python timestamp to datetime and vice-versa
Python any()