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.
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.
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
emp_details.popitem()
print(emp_details)
Returns the removed item in the form of tuple.
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)
If the dictionary is empty, raises KeyError.
emp_details = {}
emp_details.popitem()
print(emp_details)
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:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
emp_details.pop('last_name')
print(emp_details)
Removes and returns values.
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)
Raises KeyError, if the key is not found.
emp_details = {}
emp_details.pop('salary')
print(emp_details)
Avoid error by passing the second argument as None.
emp_details = {}
emp_details.pop('salary', None)
print(emp_details)
Calls custom function “my_error” in case of error.
def my_error():
print("Custom error in pop.")
emp_details = {}
emp_details.pop('salary', my_error())
print(emp_details)
The del keyword
The del keyword can be used for two purposes
- To remove an item with the specific key
- To delete the dictionary completely
Removes the specified key.
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
del emp_details['last_name']
print(emp_details)
Deletes the dictionary completely.
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
del emp_details
print(emp_details)
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.
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
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)
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
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)