If you are new to Python Dictionary, then check out this article. Dictionary is a collection of key-value pairs that are unordered, changeable, and indexed.
Python Dictionary clear()
Python Dictionary clear() is a built-in function that removes all elements from the Dictionary. The clear() function takes no parameter and doesn’t return any value.
Syntax
The syntax of the clear() method is the following.
dictionary.clear()
Let us see the example.
# app.py appDict = { 'shopping': 'flipkart', 'transport': 'ola', 'banking': 'paytm', 'hotel': 'oyo rooms' } print(appDict) appDict.clear() print(appDict)
In the above example, we created a Python Dictionary and then cleared all its elements.
See the below output.
You can also remove all elements from the Dictionary by assigning an empty dictionary {}.
# app.py appDict = { 'shopping': 'flipkart', 'transport': 'ola', 'banking': 'paytm', 'hotel': 'oyo rooms' } print(appDict) appDict = {} print(appDict)
We have assigned the empty Dictionary.
See the output.
Difference between assigning {} and clear() method?
However, there is a big difference between calling clear() and assigning {}, if there is another variable referencing to that Dictionary.
When we assign {} to the Dictionary, a new empty dictionary is created and attached to the reference. But when we do clear on the dictionary reference, the actual dictionary content is removed, so all references to the Dictionary become empty.
Python clear Dictionary is one of the Dictionary functions used to clear or remove total items (key-value pairs) from the Dictionary.
That’s it for this tutorial.
thanks for the post