Python Dictionary clear() method
Python Dictionary clear() method
The dictionary.clear() method in Python removes all the elements from a dictionary.
Syntax
dictionary.clear()
Parameter
NA
Return
None
Example 1
# Python program explaining
# the dictionary.clear() method
# initialising the dictionary
fruits = {
"banana": "apple",
"orange": "mango",
"grapes": 5
}
# initialising the dictionary
print("Dictionary:",fruits)
# clearing off all the elements from the fruits dictionary.
fruits.clear()
print("After the clear() method...")
print("Dictionary:",fruits)
Output
Dictionary: {'orange': 'mango', 'banana': 'apple', 'grapes': 5}
After the clear() method...
Dictionary: {}
Example 2
# Python program explaining
# the dictionary.clear() method
#initializing the dictionary
dictionary = {1: "numbers", 2: "digits"}
dictionary1 = dictionary
# clearing all the elements
dictionary.clear()
print('Removing all the element using clear()')
print('dictionary: ', dictionary)
print('dictionary1: ', dictionary1)
dictionary = {1: "numbers", 2: "digits"}
dictionary1 = dictionary
dictionary = {}
print('Removing all the element by assigning {}')
print('dictionary: ', dictionary)
print('dictionary1: ', dictionary1)
Output
Removing all the element using clear()
dictionary: {}
dictionary1: {}
Removing all the element by assigning {}
dictionary: {}
dictionary1: {1: 'numbers', 2: 'digits'}
