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 Program to Shuffle Deck of Cards
Python locals()
Python Program to Differentiate Between type() and isinstance()
How to get current date and time in Python?
Deep Learning in Python - LazyProgrammer
Python Shallow Copy and Deep Copy
Python Set issubset()
Python Dictionary fromkeys()
Python Program to Find All File with .txt Extension Present Inside a Directory
APIs in Node.js vs Python - A Comparison
Python String format()
Python bool()
Python Program to Swap Two Variables
Python Dictionary popitem()
Python Program to Print Output Without a Newline
Python String casefold()
Deep Learning with Python - Francois Chollet
Python abs()
Python memoryview()
Python Program to Calculate the Area of a Triangle
Python String center()
Python Program to Count the Number of Occurrence of a Character in String
Python Object Oriented Programming
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Transpose a Matrix
Python String join()
Python String rindex()
Python Tuple count()
Python Set intersection()
Python pass statement
Introduction to Scientific Programming with Python - Joakim Sundnes