python clear a dictionary banner

Python Dictionary Clear – With Examples

In python, the dictionary function clear() is used to remove all the items from a dictionary. In this tutorial we’ll look at its syntax and usage along with some examples.

Before we proceed, here’s a quick refresher on dictionaries in python – Dictionaries are a collection of items used for storing key to value mappings. They are mutable and hence we can update the dictionary by adding new key-value pairs, removing existing key-value pairs, or changing the value corresponding to a key. For more, check out our guide on dictionaries and other data structures in python.

The python dictionary function clear() can be used to remove all the items from a dictionary. Example, d.clear(). You can also set the dictionary to an empty dictionary d = {}. The difference is, d.clear() modifies the dictionary in-place while d = {} creates a new empty dictionary and assigns it to d.

The following is the syntax for using the clear() function:

sample_dict.clear()

Here, sample_dict is the dictionary you want to clear out.

Parameters: The clear() function does not take any parameters.

Returns: It does not return any value (It returns None). It modifies the list in-place, meaning the original dictionary gets modified.

Example: Use the clear function to remove a dictionary’s items

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

# dictionary of a sample portfolio
shares = {'APPL': 100, 'GOOG': 50, 'MSFT': 200}

# print the dictionary
print("Shares:", shares)

# clear the dictionary
returned_val = shares.clear()

# print the dictionary
print("Shares:", shares)
print("The returned value:", returned_val)

Output:

Shares: {'APPL': 100, 'GOOG': 50, 'MSFT': 200}
Shares: {}
The returned value: None

In the above example, the clear() dictionary function is used to remove all the items from the dictionary shares. On printing the dictionary after the function call we see the original dictionary cleared out. As for the returned value, we see that it doesn’t actually return a value, it returns None.

For more on python dictionary functions, refer to the python docs.


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top