Python Dictionary - del method with example

The del() method of the Python dictionary class dict removes a specific key-value pair corresponding to the specified key. As keys are unique in a dictionary the del() method removes only a single key-value pair from a dictionary.

Dictionary Updated 10 Sep 2016 1 min read

Function Name

del()

Parameters

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

Return Type

None

Overview

  • For the given key dict_key_in the key-value pair is removed from the Python dictionary object.
  • When dict_key_in is not found in the dictionary object a KeyError exception is raised.
  • To remove all the elements of a dictionary the clear() method is to be used.

Example

python
# 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

Output
Entries of the dictionary after del() calls:

            0:Nightingale

            1:Pacific Gull

            2:Fish Eagle

            3:Canvasback