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:
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Set discard()
Python Set union()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python String capitalize()
Python map()
Python Program to Print Output Without a Newline
Python List count()
Python String isprintable()
Java Program to Implement the Program Used in grep/egrep/fgrep
Python Global Keyword
Python eval()
Machine Learning with Python for everyone - Mark E.Fenner
Python String expandtabs()
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Data Structures and Algorithms - Benjamin Baka
Python Exception Handling Using try, except and finally statement
Python tuple()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python *args and **kwargs
Python String rindex()
Python Program to Add Two Numbers
Python Program to Multiply Two Matrices
Python List reverse()
Python Dictionary popitem()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python datetime
Python locals()
Python File I/O Operation
Python String isdigit()
Python Program to Shuffle Deck of Cards
Python print()