Python Dictionary stores elements in key-value pairs, where elements are indexed by keys and each unique key maps to a specific value. Dictionary keys can only be of immutable datatype but values can be of any datatype. Dictionary in Python, is an mutable, dynamic size collection datatype.
In previous articles, we learned to add element in dictionary and to access elements in dictionary. Similar to that, we can remove (delete) elements from dictionary in Python.
Remove elements from Dictionary
Removing any element from dictionary is an important operation and crucial in the scenarios where we need to remove some obsolete data. Example of a Python dictionary:
my_dict = {
'name': 'Alice',
'age': 30,
'city': 'Dallas'
}
Lets understand the different scenarios using which we can remove elements from the dictionary.
Using pop() method
Dictionary elements are indexed by keys and only allows only unique keys to be stored. We can use keys to access, update and remove elements from a dictionary.
Python dictionary built-in method pop(), can be used to remove elements from dictionary. Syntax for removing elements using pop() method –
value = dictionary.pop(key, default_value)
pop()method is called on a dictionary object. It can take two arguments:- key (mandatory) – key is a mandatory argument. It is the key of the dictionary element whose value we want to get and remove from the dictionary.
- default_value (optional) –
default_valueis an optional argument. If thedefault_valueparameter is passed and given key might not be present in the dictionary, thendefault_valuewill be returned. pop()method return the value of the given key from dictionary and also removes that element from the dictionary.
# remove element using pop() method
print("remove element using pop() method")
cars_dict = {"c1": "Maruti", "c2": "Hyundai", "c3": "Honda", "c4": "Toyota"}
print(cars_dict)
car_name = cars_dict.pop("c3") # pop() c3 key, present in dictionary
print(car_name) # value of key c3
print(cars_dict) # dictionary elements after removing key c3
# remove element using pop() method with default value
print("remove element using pop() method with default value")
cars_dict = {"c1": "Maruti", "c2": "Hyundai", "c3": "Honda", "c4": "Toyota"}
print(cars_dict)
car_name = cars_dict.pop("c5", "Audi") # pop() c5 key, not present in dictionary, default_value to return
print(car_name) # key c5 not present, default_value returned
print(cars_dict) # dictionary elements after removing key c5
In this program, we are defining a dictionary cars_dict. First, we are using cars_dict.pop("c3") method to get value of key c3 from dictionary and to remove element with key c3. Second, we are using cars_dict.pop("c5", "Audi") method (with default_value) to get value of key c5, which is not present in dictionary. Given default_value will be returned.
Program Output
remove element using pop() method
{'c1': 'Maruti', 'c2': 'Hyundai', 'c3': 'Honda', 'c4': 'Toyota'}
Honda # value of key c3
{'c1': 'Maruti', 'c2': 'Hyundai', 'c4': 'Toyota'} # dictionary elements after removing c3
remove element using pop() method with default value
{'c1': 'Maruti', 'c2': 'Hyundai', 'c3': 'Honda', 'c4': 'Toyota'}
Audi # default value, c5 does not exists
{'c1': 'Maruti', 'c2': 'Hyundai', 'c3': 'Honda', 'c4': 'Toyota'} # c5 does not exists, no element removed
From the output, First key exists – we got value (Honda) of element for key c3 and removed element from dictionary. Second key does not exists – we got default value Audi and no element was removed from dictionary.
Using popitem() method
Python dictionary built-in method popitem(), can be used to remove elements from dictionary. popitem() method returns the last inserted key-value pair as a tuple. Syntax for removing elements using pop() method –
key, value = dictionary.popitem() OR item= dictionary.popitem()
popitem()method is called on a dictionary object. It does not take any argument.popitem()method returns the last inserted key-value pair. Its return value can be taken in two ways.- return value as item, where item is key-value pair as a tuple
- return key and value separately.
- This method is useful when elements needs to be removed and processed in the order of their insertion.
- From Python version 3.7 and later, dictionaries maintain insertion order.
# remove last element using popitem() method
print("remove last element using popitem() method")
cars_dict = {"c1": "Maruti", "c2": "Hyundai", "c3": "Honda", "c4": "Toyota"}
print(cars_dict)
car_key, car_value = cars_dict.popitem() # key and value separately
car_item = cars_dict.popitem() # key-value pair as tuple
print(f"{car_key}, {car_value}") # print key and value separately
print(car_item) # print key-value pair as tuple
print(cars_dict) # print dictionary elements after two elements taken out
In this program, we are defining a dictionary cars_dict. We are using popitem() method two times to take out the last two elements from this dictionary. First, we are getting key and value of elements separately and second we are getting key-value as tuple.
Program Output
remove last element using popitem() method
{'c1': 'Maruti', 'c2': 'Hyundai', 'c3': 'Honda', 'c4': 'Toyota'}
c4, Toyota # key and value separately
('c3', 'Honda') # key-value pair as tuple
{'c1': 'Maruti', 'c2': 'Hyundai'} # dictionary elements after two element removed
From the output, we got c4, Toyota key and value separately and ('c3', 'Honda') key-value pair as tuple.
Error – key does not exists
pop()method throwsKeyErrorif the given key does not exists in the dictionary anddefault_valuenot given as an argument.popitem()method throwsKeyErrorif the given dictionary is empty and not element exists in it.
KeyError – pop() method
print("Error - pop() error with key not exists in dictionary")
cars_dict = {"c1": "Maruti", "c2": "Hyundai", "c3": "Honda", "c4": "Toyota"}
car_name = cars_dict.pop("c6")
We are using pop() method on dictionary cars_dict. We are trying to taken out the value of key c6 from the dictionary. Key c6 does not exists in the dictionary and no default_value passed as an argument to pop() method. It will throw an error – KeyError: c6.
Program Output
Error - pop() error with key not exists in dictionary
Traceback (most recent call last):
File "D:\remove-element-dictionary.py", line 16, in <module>
car_name = cars_dict.pop("c6")
^^^^^^^^^^^^^^^^^^^
KeyError: 'c6'
KeyError – popitem() method
# Error - popitem() error with empty dictionary
print("popitem() error with empty dictionary")
cars_dict = {}
print(cars_dict)
car_item = cars_dict.popitem()
We are using popitem() method on empty dictionary cars_dict. popitem() will try to take out the last element from the dictionary, but given dictionary cars_dict is empty. It will throw an error – KeyError: 'popitem(): dictionary is empty'.
Program Output
Traceback (most recent call last):
File "D:\remove-element-dictionary.py", line 37, in <module>
car_item = cars_dict.popitem()
^^^^^^^^^^^^^^^^^^^
KeyError: 'popitem(): dictionary is empty'
Using clear() method
clear() method is used to remove all elements from dictionary. Syntax for clear() method is:
dictionary.clear()
# remove all element using clear() method
print("remove all element using clear() method")
cars_dict = {"c1": "Maruti", "c2": "Hyundai", "c3": "Honda", "c4": "Toyota"}
print(cars_dict)
cars_dict.clear() # remove all elements from dictionary
print(cars_dict) # print empty dictionary, all elements removed
We are using cars_dict.clear() to remove all elements of dictionary cars_dict.
Program Output
remove all element using clear() method
{'c1': 'Maruti', 'c2': 'Hyundai', 'c3': 'Honda', 'c4': 'Toyota'}
{}
Using del keyword
We can use del keyword to remove particular element from dictionary or to delete entire dictionary itself.
del dictionary[key]– Syntax to remove element with the key. Removing element usingdelkeyword does not return any value.del dictionary– Syntax to delete dictionary itself
# remove element using del keyword
print("remove element using del keyword")
cars_dict = {"c1": "Maruti", "c2": "Hyundai", "c3": "Honda", "c4": "Toyota"}
print(cars_dict)
del cars_dict["c2"] # del keyword to remove key c2
print(cars_dict)
del cars_dict # del keyword to delete dictionary object
We are using del cars_dict["c2"] to remove dictionary element with key c2. Element will be removed and not value will be returned.
Program Output
remove element using del keyword
{'c1': 'Maruti', 'c2': 'Hyundai', 'c3': 'Honda', 'c4': 'Toyota'}
{'c1': 'Maruti', 'c3': 'Honda', 'c4': 'Toyota'} # element with key c2 removed from dictionary
Error – accessing element after del dictionary
After using del dictionary dictionary object will be deleted and cannot be used for any operations. if we try to perform any operation after deletion of dictionary, we will get NameError.
# delete dictionary using del keyword
print("delete dictionary using del keyword")
cars_dict = {"c1": "Maruti", "c2": "Hyundai", "c3": "Honda", "c4": "Toyota"}
print(cars_dict)
del cars_dict # dictionary deleted
print(cars_dict["c1"]) # access element after deleting dictionary
In this case, we first declared the dictionary cars_dict and then deleted it using del cars_dict. We are trying to get an element from the deleted dictionary cars_dict. it will throw an error – NameError: name 'cars_dict' is not defined
Program Output
delete dictionary using del keyword
{'c1': 'Maruti', 'c2': 'Hyundai', 'c3': 'Honda', 'c4': 'Toyota'}
Traceback (most recent call last):
File "D:\remove-element-dictionary.py", line 64, in <module>
print(cars_dict["c1"])
^^^^^^^^^
NameError: name 'cars_dict' is not defined
Summary
In this article we learned about various scenarios to remove elements from dictionary. Following methods were explored:
Code – Github Repository
All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.
Python Topics
Interview Questions & Answers
Q: How to safely remove an item from a dictionary while iterating over it?
Modification in a dictionary while iterating over it can cause runtime errors. To safely remove an item from a dictionary:
- First create a list or tuple of keys to be removed. We can create this list using list comprehension. Then iterate over this list to delete the keys from the dictionary.