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 complex()
Python datetime
Python Statement, Indentation and Comments
Python Package
Python Program to Get the Last Element of the List
Python String capitalize()
Python Program to Add Two Numbers
Python String isspace()
Python List insert()
Python if...else Statement
Python String replace()
Python bytes()
Python divmod()
Python Program to Compute the Power of a Number
Python String format()
Python Program to Check if a Key is Already Present in a Dictionary
Python Dictionary items()
Python String isdecimal()
Python issubclass()
Python String rstrip()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python classmethod()
Python @property decorator
Python memoryview()
Python Program to Count the Number of Each Vowel
Python pow()
Python String rfind()
Python List reverse()
Python Program to Access Index of a List Using for Loop
Python Program to Find the Largest Among Three Numbers
Node.js vs Python for Backend Development
Python Program to Sort a Dictionary by Value