Python Delete Key:Value from Dictionary

Delete Key:Value pair from Python Dictionary

To remove an item (key:value) pair from Python Dictionary, use pop() function on the dictionary with the key as argument to the function.

In this tutorial, we shall learn how to delete or remove a specific key:value pair from given Dictionary, with the help of well detailed example Python programs.

Syntax of dictionary pop()

Following is the syntax to delete a key:value pair from Dictionary using pop() function.

myDictionary.pop(theKey)

where myDictionary is the dictionary from which you would like to remove or delete the item with theKey as key. Also, the pop function returns the value corresponding to the key.

You can also use del keyword to remove an item using the key.

The syntax to delete a key:value pair using del keyword is given below.

del Dictionary[key]

The above expression does not return a value. It is actually a complete statement by itself.

Examples

1. Delete item from dictionary using pop()

Let us create a dictionary, initialize it and delete an item from the dictionary using pop() function.

# Create and initialize a dictionary
myDictionary = {
	'a': '65',
	'b': '66',
	'c': '67'
}

# Delete the item from the dictionary
poppedItem = myDictionary.pop('c')
print(poppedItem)

# Print the dictionary items
print(myDictionary)
Run Code Copy

Output

67
{'a': '65', 'b': '66'}

You can see that we not only deleted the item from the dictionary, but we can also store the removed item, in a variable.

2. Delete item from dictionary using del keyword

Let us create a dictionary, initialize it and delete an item from the dictionary using del keyword.

# Create and initialize a dictionary
myDictionary = {
	'a': '65',
	'b': '66',
	'c': '67'
}

# Delete the item from the dictionary
del myDictionary['c']

# Print the dictionary items
print(myDictionary)
Run Code Copy

Output

{'a': '65', 'b': '66'}

Summary

In this tutorial of Python Examples, we learned how to delete a key:value pair from Python Dictionary using pop() and del keyword, with the help of well detailed Python example programs.

Related Tutorials

Code copied to clipboard successfully 👍