How to Remove An Item from a Dictionary in Python – Definitive Guide

Python dictionary allows you to store values as a key-value pair.

You can remove an item from a dictionary using the del yourdict[“key”] statement in Python.

This tutorial teaches you the different methods to remove an item from a dictionary in Python.

If You’re in Hurry…

You can use the del statement to remove a key from a dictionary. If the key exists, it’ll delete it. Otherwise, it’ll throw a keyError.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

del yourdict["one"]

yourdict

Output

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

If You Want to Understand Details, Read on…

Different methods are available to remove a key from a dictionary in Python. Let us learn each method in detail and when it is appropriate to use them.

To just rename a key in a dictionary, read How To Rename A Key In a Dictionary Python?

Using Del Statement

The del statement removes an item from the dictionary using the key.

  • If the key is available, then the item will be deleted
  • If the key is NOT available, a KeyError will be thrown

Code

The code below demonstrates how to use the del statement to remove a key from the dictionary.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}


del yourdict["one"]

yourdict

Output

The item with key one is removed from the dictionary.

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

The following code snippet demonstrates the KeyError when you attempt to delete an item that is not available in the dictionary.

To avoid this error while using the del statement, you need to check if a key exists in a dictionary before attempting to delete it.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}


del yourdict["onee"]

yourdict

Output

    ---------------------------------------------------------------------------

    KeyError
    /var/folders/gb/19ly8vfs7t53plwx43wx1q3m0000gn/T/ipykernel_45472/1409174214.py in <module>
    ----> 9 del yourdict["onee"]
         11 yourdict

    KeyError: 'onee'

This is the usage and caveats of the del statement while using it to delete an element from the dictionary.

Using Pop

This section teaches you how to use the pop() method to delete an item from a dictionary in Python.

The pop method removes the item from the dictionary and returns the value of the removed item.

You can use this method when you want to use the value of the deleted item.

Parameters

  • Key – Key of the item to be deleted
  • Optional valueOptional – A value that needs to be returned when the key is unavailable instead of throwing a key error. If this parameter is not passed, KeyError will be thrown when the key is unavailable.
yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}


yourdict.pop("one")

Output

The item with key one is deleted, and the value of the item 1 is returned.

    1

The code below demonstrates how to use the optional parameter to return a default value instead of throwing a keyerror when the key is unavailable in the dictionary.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}


yourdict.pop("onee", "Key not found to delete")

Output

The key onee is not available in the dictionary. Hence the optional value is returned instead of throwing a KeyError.

    'Key not found to delete’

This is how you can use the pop() method to delete an item from the dictionary.

Using PopItem

The popitem() method removes the last item from the dictionary.

You need not specify the key explicitly to remove the item.

In Python versions before 3.7, a random item is removed instead of removing the last item.

Code

The code below demonstrates removing the last item from the dictionary using the popitem() method.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}


yourdict.popitem()

Output

The last item is removed from the dictionary, and both the keys and values are returned.

    ('four', 4)

This is how you can remove the element from the dictionary using the popitem() method.

Remove Multiple Keys From Dictionary

This section teaches you how to remove multiple keys from the dictionary.

There is no method directly available to delete multiple keys from a dictionary.

You can add the multiple keys to a tuple, a list, or a set and iterate over it. During each iteration, you can invoke the pop() method to remove the item with that key from the dictionary.

Code

The code below demonstrates how to remove multiple items from the dictionary using a for loop and a pop() method.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

keys_to_remove = ('one', 'two')

for key in keys_to_remove:
    print(yourdict.pop(key, None))

Output

    1
    2

Delete All Elements from Dictionary

To delete all elements from a dictionary in Python, you can use the clear() method.

It removes all items from the dictionary, but the dictionary object itself is not removed.

Code

The code below demonstrates how to delete all elements from the dictionary.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

yourdict.clear()

yourdict

Output

All the elements from the dictionary are removed, and an empty dictionary object is still available.

    {}

Delete Dictionary Key While Iterating

To delete dictionary keys while iterating, you need to iterate the dictionary keys after converting them into a list using list(yourdict.keys()).

If you iterate directly with dict.keys(), you’ll face a Runtime error. RuntimeError: dictionary changed size during iteration. This is because when you remove a key, the size of the dictionary will be changed, and the iteration cannot happen.

To learn more about deleting a dictionary key while iterating, read how to delete a key while iterating it.

Code

The code demonstrates how to delete a key from a dictionary while iterating over the list of keys.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

for k in list(yourdict.keys()):
    if k == "one":
        del yourdict[k]

yourdict

Output

The key one is removed from the dictionary while iterating over it.

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

Pop Vs Del

PopDel
Returns the value of the deleted keyReturns nothing after deleting the key
Supports an additional parameter that can be used to return a value when the key is unavailable in the dictionary. Doesn’t support an additional parameter to pass a return a value when the key is unavailable
Returns KeyError when the key is unavailableReturns KeyError when the key is unavailable
Pop vs del

Conclusion

You’ve learned how to remove an item from a dictionary using different methods and when it is appropriate to use them. You’ve also learned how to remove multiple keys, delete all elements from a dictionary and remove a key while iterating over the dictionary.

If you’ve any questions, feel free to comment below.

You May Also Like

Leave a Comment