How to Remove All Items from a Dictionary: 5 Practical Examples
You can clear all elements from a dictionary using the clear()
method. Here are five examples demonstrating how to do this:
- Clearing elements from a dictionary:
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear()
print(my_dict) # Output: {}
- Clearing elements from an empty dictionary (no effect):
empty_dict = {}
empty_dict.clear()
print(empty_dict) # Output: {}
- Clearing elements from a dictionary with mixed data types:
mixed_dict = {'name': 'John', 'age': 25, 'grades': [80, 85, 90]}
mixed_dict.clear()
print(mixed_dict) # Output: {}
- Clearing elements from a dictionary containing nested dictionaries:
nested_dict = {'a': {'x': 1, 'y': 2}, 'b': {'x': 3, 'y': 4}}
nested_dict.clear()
print(nested_dict) # Output: {}
- Clearing elements from a dictionary with default values:
from collections import defaultdict
default_dict = defaultdict(int, {'a': 1, 'b': 2, 'c': 3})
default_dict.clear()
print(default_dict) # Output: {}
In each of these examples, the clear()
method is called on the dictionary object, removing all key-value pairs from the dictionary.