In this tutorial, we will see how to remove key from dictionary in python.
How to remove key from dictionary?
dict.pop()
function is used to remove the key from a dictionary.
def remove_key(my_dict,key):
my_dict.pop(key, None)
if __name__ == '__main__':
fruits = {
1:'apple',
2:'grape',
3:'orange'
}
remove_key(fruits,2)
print(fruits)
Output:
{1: 'apple', 3: 'orange'}
The del
keyword can also be used to delete key from dictionary.
def remove_key_del(my_dict,key):
try:
del my_dict[key]
except KeyError:
pass
if __name__ == '__main__':
fruits = {
1:'apple',
2:'grape',
3:'orange'
}
remove_key_del(fruits,3)
print(fruits)
Output:
{1: 'apple', 2: 'grape'}
I always recommend you to keep the del
expression in try expect block, as it raises KeyError
if the given key does not exist in the dictionary.
Happy Learning 🙂