VOOZH about

URL: https://www.geeksforgeeks.org/python/python-remove-item-from-dictionary-by-key/

⇱ Python Remove Item from Dictionary by Key - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python Remove Item from Dictionary by Key

Last Updated : 23 Jul, 2025

Dictionaries in Python store data as key-value pairs. Often, we need to remove a specific key-value pair to modify or clean the dictionary. For instance, consider the dictionary d = {'a': 1, 'b': 2, 'c': 3}; we might want to remove the key 'b'. Let's explore different methods to achieve this.

Using del()

del() statement is the most efficient way to remove an item by its key. It directly deletes the specified key-value pair from the dictionary.


Output
{'a': 1, 'c': 3}

Explanation:

  • The del() statement identifies the key 'b' in the dictionary and removes its associated key-value pair.
  • This method is fast because it directly modifies the dictionary in place.

Let's explore some more ways and see how we can remove item from dictionary by key.

Using pop() Method

pop() method removes the key-value pair associated with a specific key and returns its value.


Output
{'a': 1, 'c': 3}
2

Explanation:

  • pop() removes the key 'b' from the dictionary and retrieves its value, which can be useful for further operations.
  • This method is slightly less efficient than del due to the return value.

Using Dictionary Comprehension

This method creates a new dictionary by filtering out the key to be removed using dictionary comprehension.


Output
{'a': 1, 'c': 3}

Explanation:

  • This method iterates through the dictionary and includes only the key-value pairs where the key is not 'b'.
  • It is less efficient because it creates a new dictionary, requiring additional memory and processing time.

Using popitem() with Manual Checks

popitem() method removes the last inserted key-value pair from the dictionary. We can use this with manual checks to find and remove a specific key, although it is not recommended for targeted key removal.


Output
{'a': 1, 'c': 3}

Explanation:

  • This method involves iterating through the dictionary and manually removing the desired key.
  • It is inefficient and should only be used in scenarios where targeted methods are not an option.
Comment
Article Tags: