How to Delete Element from Dictionary in Python
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)
Explanation
- A dictionary
myDictionary
is created and initialized with three key-value pairs:"a": "65"
,"b": "66"
, and"c": "67"
. - The
pop()
method is called to remove the item with the key"c"
from the dictionary. The method returns the value of the removed item, which is"67"
, and stores it in the variablepoppedItem
. - The
print()
function is used to display the value of the popped item, which is67
. - The dictionary is printed again, showing the remaining key-value pairs:
"a": "65"
and"b": "66"
.
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)
Explanation
- A dictionary
myDictionary
is created and initialized with three key-value pairs:"a": "65"
,"b": "66"
, and"c": "67"
. - The
del
keyword is used to remove the item with the key"c"
from the dictionary. - The
print()
function is used to display the updated dictionary, which will now show only the remaining key-value pairs:"a": "65"
and"b": "66"
.
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.