Python dictionaries are one of the most used data types. These are mutable. That is, we can add new elements or remove the existing elements or change the value of elements in a Python dictionary.
To remove the elements from a dictionary, we can use one of the following:
- pop()
- popitem()
- clear()
- del
In today’s article, let’s look at all of these functions with an example.
Recommended Reading: How to loop over Python Dictionaries?
Table of Contents
Method 1: Remove a key from the dictionary using pop()
We can use the built-in pop() method to remove a key from a Python dictionary. The Syntax of the pop() is as shown below.
dict.pop(key,default)
Parameters :
key – is the dictionary key that is to be removed.
default – is an optional parameter. The value that is to be returned if the specified key doesn’t exist.
Returns:
- If the key is in the dictionary, deletes the key-value pair.
- When the key is not in the dictionary, throws a KeyError exception.
- If the key is not in the dictionary and the default argument is provided, returns the default value.
Example 1: Remove an element from the Python dictionary using its key.
my_dict={'a':"Alice", 'b':"Bob" , 'c':"Callie" , 'd': "Dodge"} #remove the c key from the dictinary print("The popped item is ",my_dict.pop('c')) print(my_dict)
Output:
The popped item is Callie {'a': 'Alice', 'b': 'Bob', 'd': 'Dodge'}
Example 2: Remove an element from the Python dictionary using a key that doesn’t exist.
my_dict={'a':"Alice", 'b':"Bob" , 'c':"Callie" , 'd': "Dodge"} print("The popped item is",my_dict.pop('e')) print(my_dict)
Output:
Traceback (most recent call last): File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Remove a key from Python Dictionary.py", line 4, in <module> my_dict.pop('e') KeyError: 'e'
The pop() method throws an error when we try to remove a key that doesn’t exist in the dictionary. So, we have to use the pop(key) only when we are sure that the key exists in the dictionary.
In cases when we aren’t sure, we have to call pop() with the default parameter to specify the value that is to be returned when the key doesn’t exist. Refer to the below code snippet.
my_dict={'a':"Alice", 'b':"Bob" , 'c':"Callie" , 'd': "Dodge"} print("The popped item is ",my_dict.pop('e',None)) print(my_dict)
Output:
The popped item is None {'a': 'Alice', 'b': 'Bob', 'c': 'Callie', 'd': 'Dodge'}
Method 2: Remove a key from the dictionary using popitem()
We can use the popitem() to remove the last key-value pair from the dictionary. Meaning, this function removes the elements of the dictionary in the Last In First Out(LIFO) order.
Note that from Python versions 3.7 and beyond, the dictionaries are ordered. Before that, the dictionary data types were unordered. Before Python 3.7, using popitem() on a dictionary would remove a random key-value pair from the dictionary. However, from Python 3.7+, popitem() removes the last key-value pair from the dictionary.
The Syntax of popitem() is :
dic.popitem()
Parameters : None
Returns:
- Removes the last key-value pair from a dictionary.
- If the dict is empty, throws a KeyError
Example 1: Remove the last item from the dictionary
my_dict={'a':"Alice", 'b':"Bob" , 'c':"Callie" , 'd': "Dodge"} print("The popped item is",my_dict.popitem()) print(my_dict)
Output:
The popped item is ('d', 'Dodge') {'a': 'Alice', 'b': 'Bob', 'c': 'Callie'}
Example 2: Remove element from an empty dictionary
my_dict={} print("The popped item is",my_dict.popitem()) print(my_dict)
Output:
Traceback (most recent call last): File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Remove a key from Python Dictionary.py", line 3, in <module> print("The popped item is",my_dict.popitem()) KeyError: 'popitem(): dictionary is empty'
As we can see from the output, using popitem() on an empty dictionary throws an error. Hence, we should use this function when we’re sure that the dictionary is not going to be empty.
Method 3: Remove a key from the dictionary using clear()
Unlike the methods discussed above, the clear() function removes all elements from the dictionary.
Note that it clears all the contents of the dictionary. But the dictionary is not deleted. the dictionary will now be empty.
Syntax of clear() :
dict clear()
Parameters: None
Returns: None. The function does not return any values. It modifies the dictionary in place.
Let’s have a look at the example.
my_dict={'a':"Alice", 'b':"Bob" , 'c':"Callie" , 'd': "Dodge"} print("The popped item is",my_dict.clear()) print(my_dict)
Output:
The popped item is None {}
Note that, the dictionary is empty. But the dictionary exists in memory.
Method 4: Remove a key from the dictionary using del
We can use del to remove any class objects in Python. del is a keyword in Python and not a built-in function like the ones described in the above methods.
We can either delete a single element or the entire dictionary using del.
The syntax to delete an item in the dictionary.
del dict[key]
Parameter :
dict[key] – the dictionary key to be removed.
Returns: None
Working:
- If the key is in the dictionary, deletes the key-value pair from the dictionary.
- If the key is not in the dictionary, raises KeyError.
The syntax to delete the entire dictionary:
del dict
Parameter:
dict- dictionary object to be deleted.
Returns: None
Note that, del removes the dictionary from memory.
Example 1: Remove an element of the dictionary
my_dict={'a':"Alice", 'b':"Bob" , 'c':"Callie" , 'd': "Dodge"} del my_dict['b'] print(my_dict)
Output:
{'a': 'Alice', 'c': 'Callie', 'd': 'Dodge'}
Example 2: Delete an entire dictionary
my_dict={'a':"Alice", 'b':"Bob" , 'c':"Callie" , 'd': "Dodge"} print("Before deleting - ",my_dict) del my_dict print("After deleting -",my_dict)
Output:
Before deleting - {'a': 'Alice', 'b': 'Bob', 'c': 'Callie', 'd': 'Dodge'} Traceback (most recent call last): File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Remove a key from Python Dictionary.py", line 4, in <module> print("After deleting -",my_dict) NameError: name 'my_dict' is not defined
As seen from the above output, after deletion, we see an error when we try to access the dictionary.
Method 5: Using Dictionary Comprehensions
This is not exactly a method. But more of a workaround. Unlike updating the existing dictionary, we can create a new dictionary with only the elements that we want. Let’s understand this better with an example.
Say, we have a dictionary as shown below.
my_dict={'a':"Alice", 'b':"Bob" , 'c':"Callie" , 'd': "Dodge"}
Say, we want to get rid of the elements , (‘a’:”Alice”) ,(‘c’:”Callie”),(‘d’: “Dodge”). Instead of deleting all these elements from the current dictionary. We can create a new dictionary with only (‘b’:”Bob”) using comprehensions.
Here is the code snippet to create a dictionary based on conditions using dictionary comprehensions.
my_dict={'a':"Alice", 'b':"Bob" , 'c':"Callie" , 'd': "Dodge"} my_new_dict={k:v for k,v in my_dict.items() if k=='b' } print(my_new_dict)
Output:
{'b': 'Bob'}
Execution times for all the above methods
Now, let’s check which method executes faster.
from time import perf_counter_ns my_dict={'a':"Alice", 'b':"Bob" , 'c':"Callie" , 'd': "Dodge"} #Remove an element using pop() start=perf_counter_ns() my_dict.pop('a') end=perf_counter_ns() print(" Time take using pop() - %d ns"%(end-start)) #Remove an elemnt using popitem() start=perf_counter_ns() my_dict.popitem() end=perf_counter_ns() print(" Time take using popitem() - %d ns"%(end-start)) #Remove an element using del start=perf_counter_ns() del my_dict['c'] end=perf_counter_ns() print(" Time take using del - %d ns"%(end-start)) #Remove an element using clear() start=perf_counter_ns() my_dict.clear() end=perf_counter_ns() print(" Time take using clear() - %d ns"%(end-start))
Output:
Time take using pop() - 600 ns Time take using popitem() - 1300 ns Time take using del - 300 ns Time take using clear() - 600 ns
As seen from the output, to dele an item from the dictionary, del is faster compared to other methods. However, it is important to note that in a particular scenario, only the speed might not be required. We have to choose the function wisely based on all the requirements.
Conclusion:
That brings us to the end of this article. In this article, we have discussed all possible ways to delete an element from the dictionary in Python. We’ve also seen the execution times taken by each of these functions. We hope this helps you make an informed choice while choosing the right function in your program.
Kindly comment and let us if you found this article helpful.
Thanks for Reading and Happy Pythoning!
Also check, TypeError:Unhashable type dict()