Contents
Python dictionary clear() method
Python dictionary clear() method removes all the items from the dictionary.
In this tutorial, you will learn about dictionary clear() method in Python, and its usage, with the help of example programs.
Syntax of dict clear()
The syntax of dictionary clear() method is
dictionary.clear()
Parameters
The dictionary clear() method takes no parameters.
Return value
The dictionary clear() method returns None.
Please note that the clear() method removes all the items from the original dictionary. The data is lost, and therefore if you need the data later in the program, you may need to make a copy of the original dictionary.
Examples for clear() method
1. Removing all the items in the given dictionary using dict copy() method in Python
In this example, we are given a dictionary in my_dict with some initial key:value pairs. We have to remove all the items in this dictionary.
We shall call clear() method on the given dictionary object my_dict, and print the returned and print the modified dictionary to output.
Python Program
my_dict = {
'foo':12,
'bar':14,
'moo':16
}
my_dict.clear()
print(my_dict)
Run Code CopyOutput
{}
Summary
In this tutorial of Python Dictionary Methods, we learned how to use Dictionary clear() method to remove all the items from a given dictionary, with help of well detailed Python programs.