Python: Delete Dictionary Elements

There are several methods to remove items from a dictionary.

1. Using pop():

The method is used to delete with the specified key name.

Example:

dict_1={1:'a',2:'b',3:'c',4:'d'}
dict_1.pop(3)
print(dict_1)

Output: {1: 'a', 2: 'b', 4: 'd'}

2. Using del():

It can be used to delete the key that is present in the dictionary.

Example:

dict_1 = {1:'a',2:'b',3:'c',4:'d'}
del dict_1
print(dict_1)

Output: NameError: name 'dict_1' is not defined

3. Using  clear() method:

It is used to empty the dictionary.

Example:

dict_1 = {1:'a',2:'b',3:'c',4:'d'}
dict_1.clear()
print(dict_1)

Output: {}

Tags