How to remove all the elements of a dictionary in Python?

PythonServer Side ProgrammingProgramming

To remove all elements from a dictionary, the easiest way is to reassign the dictionary to an empty dictionary. 

example

my_dict = {'name': 'foo', 'age': 28}
my_dict = {}
print(my_dict)

Output

This will give the output −

{}

You can also use the del function to delete a specific key or loop through all keys and delete them.

 example

my_dict = {'name': 'foo', 'age': 28}
keys = list(my_dict.keys())
for key in keys:
  del my_dict[key]
print(my_dict)

Output

This will give the output −

{}
raja
Published on 05-Jan-2018 13:04:22
Advertisements