Ways to Remove Item from Dictionary in Python


Remove Item from Dictionary

In Python, we have various inbuilt methods and custom methods to remove items from the dictionary. In this tutorial, we will explore all one by one.

Remove Item from Dictionary

The popitem() method – Removes last inserted item

If you are using Python 3.7 or later, then the popitem() method will remove the last inserted item and if you are using Python 3.6 or earlier, then the popitem() method will remove the random item.

It returns the removed item in the form of the tuple and raises the KeyError if the dictionary is empty.

Removed the last item.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
emp_details.popitem()
print(emp_details)
{'first_name': 'Tim', 'last_name': 'Cook', 'emp_id': 200}

Returns the removed item in the form of tuple.

In [2]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
removed_item = emp_details.popitem()

print(removed_item)
print(emp_details)
('bill', 200.2)
{'first_name': 'Tim', 'last_name': 'Cook', 'emp_id': 200}

If the dictionary is empty, raises KeyError.

In [3]:
emp_details = {}
emp_details.popitem()
print(emp_details)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-4dff3dde114d> in <module>
      1 emp_details = {}
----> 2 emp_details.popitem()
      3 print(emp_details)

KeyError: 'popitem(): dictionary is empty'

The pop() method – Removes item with specific key

The pop() method is useful to remove an item with the specific key. It returns the value of the item it removed.

The KeyError is raised if the item is not present in the dictionary. To avoid the error, we can pass the second argument as the “None”. To call a custom function on the error, the function is passed as the second argument.

Let us take a look at the examples below:

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
emp_details.pop('last_name')
print(emp_details)
{'first_name': 'Tim', 'emp_id': 200, 'bill': 200.2}

Removes and returns values.

In [2]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
removed_item = emp_details.pop('last_name')

print(removed_item)
print(emp_details)
Cook
{'first_name': 'Tim', 'emp_id': 200, 'bill': 200.2}

Raises KeyError, if the key is not found.

In [3]:
emp_details = {}
emp_details.pop('salary')
print(emp_details)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-165462751f47> in <module>
      1 emp_details = {}
----> 2 emp_details.pop('salary')
      3 print(emp_details)

KeyError: 'salary'

Avoid error by passing the second argument as None.

In [4]:
emp_details = {}
emp_details.pop('salary', None)
print(emp_details)
{}

Calls custom function “my_error” in case of error.

In [5]:
def my_error():
    print("Custom error in pop.")

emp_details = {}
emp_details.pop('salary', my_error())
print(emp_details)
Custom error in pop.
{}

The del keyword

The del keyword can be used for two purposes

  1. To remove an item with the specific key
  2. To delete the dictionary completely

Removes the specified key.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
del emp_details['last_name']
print(emp_details)
{'first_name': 'Tim', 'emp_id': 200, 'bill': 200.2}

Deletes the dictionary completely.

In [2]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
del emp_details
print(emp_details)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-2a39843f6733> in <module>
      1 emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
      2 del emp_details
----> 3 print(emp_details)

NameError: name 'emp_details' is not defined

The clear() method – to empty the dictionary

The clear() method removes all the items from the dictionary. The dictionary variable still exists with no data.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
emp_details.clear()
print(emp_details)
{}

Dictionary Comprehension

Using this approach, we cannot directly delete items from the dictionary, but we will create a new dictionary with the required items. This means it is not the in-place deletion. But technically, we have removed all the unwanted items from the new dictionary. Let us understand using an example. In the below example, we have a dictionary of marks. Here, we want to remove all those marks are greater than 50 to find out failures. We can achieve this using a condition for marks < 50 and store the result in a new dictionary.

Failure if Marks < 50

In [1]:
marks = {"Sam": 45, "Steve": 78, "Elon": 88, "Bill": 65, "Tim": 49}

failures = {key:value for key, value in marks.items() if value < 50}
        
print(failures)
{'Sam': 45, 'Tim': 49}

Using for loop

A simple for loop to iterate over all the items of the dictionary followed by the if statement will do the job. The items are not removed from the original dictionary, but we will create a new dictionary with the required items.

Failure if Marks < 50

In [1]:
marks = {"Sam": 45, "Steve": 78, "Elon": 88, "Bill": 65, "Tim": 49}

failures = {}

for key, value in marks.items():
    if value < 50:
        failures[key] = value
        
print(failures)
{'Sam': 45, 'Tim': 49}

References

  1. Remove an item from a dictionary in Python
  2. Python Removing Items from a Dictionary