Sometimes there are too many elements present in a dictionary. Deleting all the key-value pairs one after the other is a very time-taking process. This is where the clear dictionary python built-in method comes in handy.
The clear dictionary python is used to erase all the elements present inside the dictionary.
Syntax:
dict.clear()
dict-is the name of the dictionary.
clear() Parameters
The clear dictionary python method does not take any parameters as input from the user.
Return Value from clear()
There are no values returned after using the clear().
Example 1: How clear() method works for dictionaries?
dict11 = {1: "one", 2: "two"}dict11.clear()print('dict =', dict11)Outputdict = {}
How do you clear a dictionary?
To clear all the elements present inside a dictionary, the clear() is used. Look at the example given below to understand how it works:
Source Code:
phone = {"brand": "Apple","model": "12 pro","year": 2020}phone.clear()print(phone)Output:{}
What does Clear () do in Python?
The clear dictionary python is used when the user wants to erase all the elements present inside a dictionary.
For Example:
text11 = {1: "studying", 2: "python", 3: "is", 4:"fun"}text11.clear()print('text =', text11)Output:text11 = {}
What is the purpose of the clear method in a dictionary?
The clear method in python is used to erase all the elements present inside the dictionary. It does not take any parameters from the user and has to return value. It returns an empty dictionary with no elements.
Look at the example below for a better understanding:
Source Code:
dict = {'Name': 'Johnny', 'Age': 17};print ("Start Length of the dictionary:", len(dict))dict.clear()print ("End Length of the dictionary:", len(dict))Output:Start Length of the dictionary: 2End Length of the dictionary: 0
What is the difference between the Del and clear () method of dictionary?
The del keyword in python deletes the objects.
Syntax:
del object_name
Lists, elements within lists, variables, user-defined objects, dictionaries, and so on are all examples of object_name.
On the other hand, the clear() erases the elements in the dictionary.
Source Code:
class MyClass1:ab = 10def funct(self):print('Hello')# Output:print(MyClass1)# deleting MyClass1del MyClass1# Error: MyClass1 is not defined as we deleted itprint(MyClass1)Output:Traceback (most recent call last):File "./prog.py", line 13, in NameError: name 'MyClass1' is not defined