Python Dictionary Clear: How to Remove Dictionary Element

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.

Python Dictionary Clear Example | clear() Method Tutorial

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.

Python Dictionary Clear Example

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.

1 thought on “Python Dictionary Clear: How to Remove Dictionary Element”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.