How to clear a dictionary in Python
How to clear a dictionary in Python.
Here's a step-by-step tutorial on how to clear a dictionary in Python:
Step 1: Create a dictionary
First, let's start by creating a dictionary to work with. You can create a dictionary by enclosing key-value pairs within curly braces {}.
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
Step 2: Using the clear() method
To clear a dictionary in Python, you can use the clear() method. This method removes all the key-value pairs from the dictionary, effectively making it empty.
my_dict.clear()
Step 3: Verify the dictionary is cleared
You can verify that the dictionary is cleared by printing it after clearing. In this case, the output will be an empty dictionary.
print(my_dict)
Output:
{}
Step 4: Clearing a nested dictionary
If your dictionary contains nested dictionaries, you can use the clear() method to clear the nested dictionaries as well. Here's an example:
my_dict = {'name': 'John', 'age': 25, 'address': {'city': 'New York', 'country': 'USA'}}
my_dict['address'].clear()
print(my_dict)
Output:
{'name': 'John', 'age': 25, 'address': {}}
In the above example, the nested dictionary 'address' is cleared while keeping the other key-value pairs intact.
Step 5: Reassigning an empty dictionary
Instead of using the clear() method, you can also reassign an empty dictionary to clear it. Here's an example:
my_dict = {'name': 'John', 'age': 25}
my_dict = {}
print(my_dict)
Output:
{}
In this case, the dictionary is cleared by assigning an empty dictionary literal to the variable.
That's it! You now know how to clear a dictionary in Python using the clear() method or by reassigning an empty dictionary.