Python Dictionary clear() Function
The Dictionary clear() method removes all items from the dictionary.
This method does not return anything: it modifies the dictionary in place, leaving it empty.
Syntax
my_dictionary.clear()
clear() Parameters
Python Dictionary clear() function does not take any parameters.
clear() Return Value
Python Dictionary clear() function does not return any value.
Examples
Example 1: Clear a Dictionary
Let's use clear() to remove all the items from the dictionary:
my_dict = {1: "Tutorial", 2: "Reference", 3:"tutorialreference.com"}
my_dict.clear()
print(my_dict) # {}
output
{}
Example 2: Clear a list of dictionaries
Let's use clear() method to remove all key-value pairs from each dictionary within a list. By iterating over each dictionary in list_of_dict and calling clear() on each, the contents of each dictionary are removed, resulting in a list of empty dictionaries.
# List of dictionaries
list_of_dict = [
{'Name': 'Tom', 'Age': 35},
{'Name': 'David', 'Age': 25},
{'Name': 'Anna', 'Age': 23},
{'Name': 'Ryan', 'Age': 28},
]
print('Original Dictionary:')
print(list_of_dict)
# Clear all dictionaries in a list of dictionaries
for elem in list_of_dict:
elem.clear()
print('Updated Dictionary:')
print(list_of_dict)
output
Original Dictionary:
[{'Name': 'Tom', 'Age': 35}, {'Name': 'David', 'Age': 25}, {'Name': 'Anna', 'Age': 23}, {'Name': 'Ryan', 'Age': 28}]
Updated Dictionary:
[{}, {}, {}, {}]
clear() vs Assigning an Empty Dictionary
Assigning an empty dictionary my_dictionary = {} is not same as my_dictionary.clear().
For example,
old_dict = {'name': 'Tom', 'age': 25}
new_dict = old_dict
old_dict = {}
print(old_dict) # Output: {}
print(new_dict) # Output: {'age': 25, 'name': 'Tom'}
output
{}
{'name': 'Tom', 'age': 25}
The difference is that old_Dict = {} does not empty the dictionary in-place, it just overwrites the variable with a different dictionary which happens to be empty.
If anyone else like new_Dict had a reference to the original dictionary, that remains as-is.
In contrast, the clear() method empties the dictionary in-place. Thus, all references are also cleared.
old_dict = {'name': 'Tom', 'age': 25}
new_dict = old_dict
old_dict.clear()
print(old_dict) # Output: {}
print(new_dict) # Output: {}
output
{}
{}