Python Dictionary clear()
The dict.clear()
method removes all the key-value pairs from the dictionary.
Syntax:
dict.clear()
Parameter:
No parameters.
Return type:
None.
The following example demonstrates the dict.clear()
method.
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5 }
print("Dictionary: ", romanNums)
romanNums.clear()
print("Dictionary after calling clear() method: ", romanNums)
Dictionary: {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5}
Dictionary after calling clear() method: {}
The keys of the dictionary can also be integers. The clear() method will still work.
numdict = {1:'one',2:'two',3:'three',4:'four',5:'five'}
print("Dictionary: ", numdict)
numdict.clear()
print("Dictionary after calling clear() method: ", numdict)
Dictionary: {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
Dictionary after calling clear() method: {}