Python Dictionary: clear() function & examples

In this article we will discuss how to use the clear() method of dict class in python.

dict.clear() Syntax:

In python, the dict class provides a member function to empty a dictionary i.e.

dict.clear()
  • Parameters: None
      • It does not take any parameter.
  • Returns: None
      • It does not return any value.

It deletes all the elements from the dictionary in place and does not return any thing.

Let’s understand with some examples

dict.clear() Examples

Empty a dictionary python

Suppose we have a dictionary of strings & integers as keys-value pairs. We want to delete all items i.e. key-value pairs from this dictionary. For that we can use the clear() function,

# Dictionary of string and int
word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78
}

print('Original Dictionary:')
print(word_freq)

# Remove all key-value pairs from the dictionary
word_freq.clear()

print('Updated Dictionary:')
print(word_freq)

Output:

Original Dictionary:
{'Hello': 56, 'at': 23, 'test': 43, 'this': 78}
Updated Dictionary:
{}

With a simple function call clear() ,we deleted all elements from the dictionary and now our dictionary is empty.

Clear all dictionaries in a list of dictionaries

Suppose we have a list of dictionaries and we want to convert this to a list of empty dictionaries i.e. we want to delete the contents of each of the dictionary in list. Let’s see how to do that,

# List of dictionaries
list_of_dict = [
    {'Name': 'Shaun', 'Age': 35},
    {'Name': 'Ritika', 'Age': 31},
    {'Name': 'Smriti', 'Age': 33},
    {'Name': 'Jacob', 'Age': 23},
]

print('Original Dictionary:')
print(list_of_dict)

# Clear all dictionaries in a list of dictionaries
for elem in list_of_dict:
    elem.clear()

print('Updated Dictionary:')
print(list_of_dict)

Output:

Original Dictionary:
[{'Name': 'Shaun', 'Age': 35}, {'Name': 'Ritika', 'Age': 31}, {'Name': 'Smriti', 'Age': 33}, {'Name': 'Jacob', 'Age': 23}]
Updated Dictionary:
[{}, {}, {}, {}]

Here we iterated over each dictionary in the list and called the clear() function on that dictionary, which removed all key-value pairs from that dictionary. So, now we have a list of empty dictionaries.

This is how we can delete all elements from dictionary in python using dict.clear() method.

Leave a Comment

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

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

Scroll to Top