Dictionary clear() method in Python

In this article, we would cover Dictionary clear() method in Python. We already know from here (Dictionaries in Python), that a dictionary contains key:value pairs. In certain situations, we need to remove all the key:value pairs or items in one go.

Deleting each item manually is definitely not the preferred option. What if we could delete all the items of a dictionary in one go. This is made possible through clear() method. The clear() method clears all the items in a dictionary.

The syntax for clear() method is –

dict.clear()

Next, we understand the concept with appropriate examples.

Dictionary clear() method in Python

Example. Let’s say we have a dictionary x,

x = {"status": "draft", "post": 354, "name": "TechPiezo"}

Use print() method to check for the items –

print(x)

It would return with –

{'status': 'draft', 'post': 354, 'name': 'TechPiezo'}

Now, to delete all the items at once – we use clear() method

x.clear()

Again, to see the changes – print() method –

print(x)

This time around, it would return with an empty dictionary (i.e. just the curly brackets)-

{}

In conclusion, we have discussed Dictionary clear() method in Python.

Additional Info –

In this section, we would cover – what if we wish to delete only a specific key:value pair. Then, in that case – we use del. So, this is how it works –

del mydict[key]

The above will delete the item associated with that particular key. Let’s understand it with an example –

x = {"status": "draft", "post": 354, "name": "TechPiezo"}

If we wish to delete the value associated with “post” key. Then, use –

del x["post"]

Now, to check for the changes – we use print() method –

print(x)

It would return with –

{'status': 'draft', 'name': 'TechPiezo'}

Clearly, we can see the key:value pair or the item associated with “post” key and value have been deleted from the dictionary.