How to Clear a Python Dictionary?

Estimated read time 1 min read

In Python, you can clear all key-value pairs from a dictionary by using the clear() method. The clear() method removes all key-value pairs from the dictionary, leaving it empty.

Here’s an example of how to use the clear() method to clear a dictionary:

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear()
print(my_dict) # Output: {}

In this example, the clear() method is called on the my_dict object, which removes all key-value pairs from the dictionary, leaving it empty.

Note that the clear() method modifies the original dictionary in place and does not return a new dictionary. If you want to create a new dictionary with the same name as the original dictionary, you can simply assign an empty dictionary to it like this:

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict = {}
print(my_dict) # Output: {}

This creates a new empty dictionary and assigns it to the my_dict variable, effectively clearing all key-value pairs from the original dictionary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply