Dictionary clear() method Python

The Python Dictionary clear( ) method purpose is to delete all the items of the dictionary.This ethod has no other purpose.The method does not accept any argument.

>>> d={ 21:45 , 78:19 , 'text':'New' , '01001':"Happ" }
>>> d.clear()
>>> d
{}
>>> d1={} #empty dictionary
>>> d1.clear()
>>> d1
{}

It seems deleting an empty dictionary using the clear() method is acceptable.


Another way to delete an item from the dictionary is to use the ‘del‘ statement

Using ‘del‘ we can delete an item from the dictionary.The format of using ‘del’ is simple:
 
del D1[ key ]
 
The ‘D1‘ is the dictionary object and the ‘key’ is the key of the item which should be deleted from the dictionary.

>>> d1={ 23:78 , 'Text':'Heap' , 'New':'Newer' , 'Normal':'abnormal' }
>>> del d1[23]
>>> d1
{'Text': 'Heap', 'New': 'Newer', 'Normal': 'abnormal'}
>>> del d1['Normal']
>>> d1
{'Text': 'Heap', 'New': 'Newer'}

If you want to delete the entire object completely you can do so using ‘del’ but note after this the object cannot be used again.

>>> d1={ 23:78 , 'Text':'Heap' , 'New':'Newer' , 'Normal':'abnormal' }
>>> del d1
>>> d1
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    d1
NameError: name 'd1' is not defined

The error “name ‘d1’ is not defined” means the object is completely deleted,if you want to use ‘d1’ again you have to declare it again.



Leave a Reply

Your email address will not be published. Required fields are marked *