3 ways to delete a key from a dictionary in python

As we all know the dictionary is one of the most used and popular data type in the python programming language. Dictionaries are made up of key-value pairs. Deleting a key will also delete its corresponding value from the dictionary.

Consider the following dictionary numbers. This dictionary consists of numbers in words as key and the number as the value.

# dictionary
numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4,  'five': 5}

We can remove or delete the key from this dictionary using the following three methods.

  1. pop()
  2. popitem()
  3. del()

Let us look at each method one by one with an example for each method.

pop()

The pop method will take one argument – the key to be deleted. This method will remove the key from the original dictionary and return the value of the popped key.

numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4,  'five': 5}

item = numbers.pop('one')
print(item)
print(numbers)

The output of the above code is,

1
{'two': 2, 'three': 3, 'four': 4, 'five': 5}

popitem()

The popitem() method will not require any arguments. It will remove the last key-value pair from the dictionary. This method will return the removed key-value pair as a tuple.

numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4,  'five': 5}

item = numbers.popitem()
print(item)
print(numbers)

The output of the above code is,

('five', 5)
{'one': 1, 'two': 2, 'three': 3, 'four': 4}

del()

The last option is using the del() method. This is a default keyword from python unlike the above two methods. This will not return and hence cannot be assigned to any variables. This will change/remove the key-value pair from the original dictionary.

numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4,  'five': 5}

del numbers['one']
print(numbers)

The output of the above code is,

{'two': 2, 'three': 3, 'four': 4, 'five': 5}

Conclusion

Hope this article is helpful. It is always better to know all the possible ways of doing a task. I have always known only about the del keyword for a long time.

Happy coding!

5 thoughts on “3 ways to delete a key from a dictionary in python

Leave a Reply

Your email address will not be published. Required fields are marked *