How to Clear or Empty a Dictionary in Python


Delete all items of a Python Dictionary

To clear or empty a dictionary, which means deleting all the items in the dictionary, use clear() function.

In this tutorial, we shall learn how to clear all the items in a Python Dictionary using Dictionary.clear() function, with the help of syntax and well detailed example Python programs.


Syntax of Dictionary.clear()

Following is the syntax to clear items in a Dictionary.

Dictionary.clear()

The elements in the original dictionary are removed. This operation results in a loss of data. So, exercise caution while you call clear() on Dictionary.


Examples

1. Clear all items in a given Dictionary

We will create a dictionary, initialize it with some key:value pairs, and then delete all of them using clear() function.

Python Program

myDictionary = {
	"a": 65,
	"b": 66,
	"c": 67
}

# print the dictionary items
print('Dictionary items:\n',myDictionary)

# clear the dictionary
myDictionary.clear()

# print the dictionary items
print('Dictionary items after clear():\n',myDictionary)

Explanation

  1. A dictionary myDictionary is created and initialized with three key-value pairs: "a": 65, "b": 66, and "c": 67.
  2. The print() function is used to display the dictionary items before clearing, which are:
  • "a": 65
  • "b": 66
  • "c": 67
  • The clear() method is called on the dictionary, which removes all items from it.
  • The print() function is used again to display the dictionary items after the clear() method has been called, showing an empty dictionary.
  • Output

    Dictionary items:
     {'a': 65, 'b': 66, 'c': 67}
    Dictionary items after clear():
     {}

    Summary

    In this tutorial of Python Examples, we learned how to clear or empty a Python Dictionary using clear(), with the help of well detailed Python example programs.


    Python Libraries