Open In App

Python Remove Item from Dictionary by Key

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Python
d = {'a': 1, 'b': 2, 'c': 3}

# Remove the key 'b'
del d['b']

# The updated dictionary
print(d)

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.

Python
# Initialize the dictionary
d = {'a': 1, 'b': 2, 'c': 3}

# Remove the key 'b' and store its value
val = d.pop('b')

# The updated dictionary
print(d) 
print(val)  

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.

Python
d = {'a': 1, 'b': 2, 'c': 3}

# Remove the key 'b' using dictionary comprehension
d = {k: v for k, v in d.items() if k != 'b'}

# The updated dictionary
print(d)

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.

Python
d = {'a': 1, 'b': 2, 'c': 3}

# Manually check and remove the desired key-value pair
for key in list(d.keys()):
    if key == 'b':
        del d[key]

# The updated dictionary
print(d)

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.

Practice Tags :

Similar Reads