Python Dictionary - del method with example

Function Name:

del()

Function Type:

Works like a built-in function as the dict class implements the __del__() method.

Parameters:

dict_key_in – The key for which the key-value pair to be deleted in the python dictionary.

Return Type:

None

Exception Handling:

If the dict_key_in is not found in the python dictionary a KeyError exception will be raised.

Example:

# Example Python program that deletes a key-value
# pair from a dict instance

# Create a dictionary
birds = {0:"Nightingale",
         1:"Pacific Gull",
         2:"Fish Eagle",
         3:"Canvasback",
         4:"Dodo",
         5:"Moa"};

# Delete an extinct bird
del(birds[5]);

# Delete another extinct bird
del(birds[4]);

print("Entries of the dictionary after del() calls:");
for item in birds:
    print("%d:%s"%(item, birds[item]));

 

Output:

Entries of the dictionary after del() calls:
0:Nightingale
1:Pacific Gull
2:Fish Eagle
3:Canvasback


Copyright 2024 © pythontic.com