Clear a Dictionary in Python

Clearing a dictionary means removing all its key-value pairs, resulting in an empty dictionary. In this blog post, we will explore different methods to clear a dictionary in Python.

Method 1: Using the clear() Method

# Method 1: Using the clear() Method
my_dict = {"name": "John", "age": 30, "city": "New York"}
my_dict.clear()
print("Cleared dictionary:", my_dict)

Output:

Cleared dictionary: {}

Method 2: Reassigning an Empty Dictionary

# Method 2: Reassigning an Empty Dictionary
my_dict = {"name": "John", "age": 30, "city": "New York"}
my_dict = {}
print("Cleared dictionary:", my_dict)

Output:

Cleared dictionary: {}