You can remove all items from a dictionary in Python using the clear()
method. This method empties the dictionary, leaving it with zero items. It
does not take any parameters and does not return a value. Here's how you use
it:
python
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear()
print(my_dict) # Output: {}
After calling clear()
, the dictionary becomes empty {}
. Alternatively, you can also remove all items by reassigning the dictionary to an empty dictionary:
python
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict = {}
print(my_dict) # Output: {}
Or, if you want to remove items one by one, you could iterate over the keys
and delete them using del
in a loop, but this is less efficient than
clear()
. In summary, the simplest and most common way to remove all items from a
dictionary is to use the clear()
method.