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 hex()
Python Set add()
Python String join()
Python String maketrans()
Python Variables, Constants and Literals
Python Set pop()
Python String rfind()
Python Program to Create a Countdown Timer
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Program to Merge Two Dictionaries
Python Set copy()
Python List remove()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Program to Extract Extension From the File Name
Python open()
Python Program to Check if a Number is Odd or Even
Python @property decorator
Python Program to Compute the Power of a Number
Python frozenset()
Python String isdigit()
Python strftime()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python while Loop
Python Program to Find the Sum of Natural Numbers
Python String isprintable()
Python Program to Find Sum of Natural Numbers Using Recursion
Python Errors and Built-in Exceptions
Python Program to Convert Decimal to Binary Using Recursion
Python Multiple Inheritance
Python List reverse()
Python frozenset()