Python Dictionary clear()

In this blog post, you’ll learn about the Python Dictionary clear() method. But, before I cover the clear() method I would like to give a brief definition of what a Python Dictionary is.

Definition: A Python dictionary data structure is a collection of key-value pairs that are unordered, and are accessed by a key instead of an index. You can kind of think of a dictionary as a collection of variables with associated values that all have something in common.

As you read over the article, you can watch my explainer video on the dict.clear() method:

Dictionary Syntax

Python Dictionaries use a very simple syntax, making it convenient to perform common operations on dictionaries, such as accessing, updating, and deleting items of a dictionary. Here’s a quick view of what the dict syntax looks like:

# declaring an empty dictionary:
dict = {}

# declaring a dictionary containing n key-value pairs:
# dict = {key_1: value, key_2: value, key_3: value, …, key_n: value}

The above dictionary declares a collection of key-value pairs, each associated key and value are separated by the colon (:) symbol, the collection of key-value pair items are then separated by commas, which are then are stored inside of a dict data structure, represented as the curly braces ({}) symbol. The keys can store any value and those values can be the same, but the keys themselves must be unique as indicated above.

# syntax to delete a single item from a dict:
del dict[key]

Python dict.clear() method

Python dict.clear() is a method that removes all elements of a dictionary. Here’s some features of the clear() method:

Syntax:

dict.clear() # clears all the contents of dict

Parameters:

Not applicable, the dict.clear() method does not take any parameters.

Return Values:

The dict.clear() method does not return any values, it only performs a clear operation by modifying the dictionary in-place.

Python dict.clear() method used in practice

Ok, so now that we’ve covered what the Python dict.clear() method is and covered it’s syntax, the next step is to show how the dict.clear() method is used in practice by doing some examples.

How to Delete an Item From a Dictionary?

# declare dict:
items_dict = {'ebooks': 4, 'laptops': 1, 'backpacks': 3}
# print dict:
print(items_dict)

# delete an time from the dict based on a key:
del items_dict['ebooks']

# print the updated dict:
print(items_dict)

# console execution and output:
# > python script.py
# {'ebooks': 4, 'laptops': 1, 'backpacks': 3}
# {'laptops': 1, 'backpacks': 3}

As you can see from the above example, the {‘ebooks’: 4} key-value pair gets cleared from the items_dict.

How to Clear All Elements of a Dictionary?

# initialize a python dict:
fruit_dict = {'mangos': 3, 'bananas': 2, 'melons': 5}

print(fruit_dict) # print original dictionary:

# print the length of original dict:
print("length of fruit_dict: %d" % len(fruit_dict))

# delete all items from fruit_dict:
fruit_dict.clear()

# print updated dict:
print(fruit_dict)

# print length of updated dict:
print("length of fruit_dict: %d" % len(fruit_dict))

# console results:
# > python script.py
# {'mangos': 3, 'bananas': 2, 'melons': 5}
# length of fruit_dict: 3
# {}
# length of fruit_dict: 0

In the above example, a fruit dict is declared, then the length of the fruit dict is printed to the console printing three key-value pairs. In the next step the dict clear() method is called on and applied to the fruit dict. When the fruit dict’s length again gets printed to the console, it’s new updated length is 0, because the python dict clear() method cleared out all the key-value pair elements from the fruit dict, leaving it as an empty dict({}).

What’s the Difference Between Assigning an Empty dict vs clear()?

This next example will show how assigning an empty dict (dict = {}) is different to clearing a dict (dict.clear()):

Assigning an empty dict({}):

full_name_dict = {'fst_name': 'bill', 'lst_name': 'mark'}
updated_name_dict = full_name_dict
full_name_dict = {}

print(full_name_dict) # prints {}
print(updated_name_dict) # prints original dict before update

# console results:
# > python script.py
# {}
# {'fst_name': 'bill', 'lst_name': 'mark'}

So full_name_dict = {} overwrites the older dict with a new empty dict, so this operation does not empty the original dictionary in-place. The reference updated_name_dict, as full_name_dict remains as-is, as shown in the console results.

Using dict.clear() method:

full_name_dict = {'fst_name': 'jim', 'lst_name': 'bill'}
updated_name_dict = full_name_dict
full_name_dict.clear() # empties dict

print(full_name_dict) # prints {}
print(updated_name_dict) # prints {}

# console results:
# > python script.py
# {}
# {}

Opposed to assigning an empty dict, the clear() method clears the dict in-place, which means that the references will also be cleared. As you can see by the output, the clear() method clears the dict in-place, so the older references get cleared out as well.

How to Remove Elements From a Dictionary While Iterating Over It?

You may encounter a case where it’s required to clear just a single item from a dict while iterating over it. You can also do this operation by setting some criteria where if a dict key equals some value, then that item will be deleted from the dict.

# declare a dict:
fruit_dict = {'bananas': 6, 'apples': 2, 'watermelon': 3}

# prints original dict
print(fruit_dict)

# iterate through dictionary with a criteria set:
for key in list(fruit_dict.keys()):
	if fruit_dict[key] == 2:
    	  del fruit_dict[key]

print(fruit_dict) # print dict after iteration operation.   	 
# console results:
# > python script.py
{'bananas': 6, 'apples': 2, 'watermelon': 3}
{'bananas': 6, 'watermelon': 3}

In this for loop the dict.keys() method is used to access the keys of the dict, which then need to be converted during the operation to avoid iterator errors, from there the for loop iterates through each key, then each iteration passes through an if statement, where if a key is equal to some value, then that key-value pair will be deleted from the dict, as shown by reprinting the dict.