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 getattr()
Python Program to Safely Create a Nested Directory
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python tuple()
Python List remove()
Python Functions
Python Program to Return Multiple Values From a Function
Python Program to Make a Simple Calculator
Python Program to Count the Occurrence of an Item in a List
Python sleep()
Python slice()
Python Dictionary pop()
Python Program to Check Leap Year
Python map()
Python Program to Iterate Through Two Lists in Parallel
Python Dictionary popitem()
Python dir()
Python Iterators
Python Operators
Python List pop()
Python Program to Check If Two Strings are Anagram
How to get current date and time in Python?
Python Program to Get a Substring of a String
Python Decorators
Python Type Conversion and Type Casting
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python super()
Python Errors and Built-in Exceptions
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Anonymous / Lambda Function
Python dict()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda