Python Dictionary clear() With Examples

Python Dictionary clear

Now, we are going to learn about the clear method in relation to the dictionary. As the name of the method says, the clear method clears the dictionary, which means that all the elements are removed from the dictionary. So, if you want to remove all the elements from the dictionary, you can make use of the clear method.

Let’s have a look at an example, where we are trying to use the clear method –

Python Dictionary clear()

As you can see, in the above program, we have a sample dictionary, after that, we are trying to print that sample dictionary, and then we have called the clear method on the sample dictionary. The clear method removes all the elements from the dictionary, and after that, we are trying to print the dictionary again, and we get an empty dictionary.

Let’s have a look at the output of the above program now.

C:\Users\GyaniPandit\Desktop\python> python dictionary.py
{‘one’: 1, ‘two’: 2, ‘three’: 3}
{}

So, as you can see from the output, we got the dictionary cleared, using the clear method. So, we can make use of the clear method, as and when required in the python programs. Remember that the clear method removes all the elements from the dictionary.