The clear() method of Python dictionary

The clear() method removes all the elements from a Python dictionary object and makes the dictionary empty. The length of the dictionary becomes zero.

Dictionary Updated 10 Sep 2016 1 min read

Method Name

clear

Method Signature

clear()

Return Value

None

Overview

  • The clear() method of the dict class removes all the elements from a Python dictionary object.
  • As all the elements of a dictionary are removed through the clear() method the length of the dictionary becomes zero.
  • While the dictionary methods del(), pop() and popitem() remove one single key-value pair from a dictionary the clear() method removes all the elements of a dictionary and makes the dictionary empty.

Example

python
# Example Python program that removes

            # all the elements from a Python dictionary

            expiredOrders = {1:"Expired",

                             10:"Expired",

                             14:"Expired",

                             15:"Expired"}

            expiredOrders.clear()

            print("Length of dictionary after removing all items:")

            print(len(expiredOrders))

Output

Output
Length of dictionary after removing all items:

            0