remove all items from a python dictionary

Remove All Keys From Python Dictionary

In this tutorial, we will look at how to remove all the key-value pairs from a Python dictionary with the help of some examples.

How to remove all items from a dictionary in Python?

remove all items from a python dictionary

You can use the Python dictionary clear() function to remove all the key-value pairs from a dictionary. The following is the syntax –

# remove all dictionary items
my_dict.clear()

It removes all the items in the dictionary in place thereby resulting in an empty dictionary.

Let’s look at some examples.

You have a dictionary containing the names to department mapping of employees in an office. Unfortunately, management has decided to close down this branch and lay off the employees.

You need to update the employee dictionary such that there are no items present in the dictionary.

# create a dictionary
employees = {
    "Jim": "Sales",
    "Dwight": "Sales",
    "Angela": "Accounting"
}
# remove all items from dictionary
employees.clear()
# display the dictionary
print(employees)

Output:

{}

Here we used the dictionary clear() function to remove all the key-value pairs from the employees dictionary. The employees dictionary is now empty.

📚 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.

Note that the clear() function modifies the dictionary in-place.

Let’s look at another example.

# create a dictionary
test_scores = {
    "Chad": 91,
    "Hasan": 98
}
# remove all items from dictionary
test_scores.clear()
# display the dictionary
print(test_scores)

Output:

{}

The test_scores dictionary originally contained two key-value pairs. We get an empty dictionary after using the dictionary clear() function.

You might also be interested in –

  1. Remove Key From a Dictionary
  2. Check If a Python Dictionary Contains a Specific Key
  3. Check If a Dictionary Is Empty In Python


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