To remove an element from the dictionary in Python, you can use the dict.pop() method or del operator to remove the key.
Python Dictionary is used in various practical applications such as day-day programming, web development, AI/ML programming, and data science application, making it a useful container overall.
Removing a key from a dictionary using the del
Python del keyword can be used to inplace delete the key in the dictionary.
One drawback that can be thought of using this is that it raises an exception if the key is not found, and hence non-existence of the key has to be handled.
The syntax for Python del() is the following.
del d[key]
The del statement removes the given item from the dictionary. If the given key is not present in the dictionary, it will throw KeyError.
See the following code.
# app.py netflix_dict = {"Stranger Things" : 11, "You" : 3, "BoJack Horseman" : 21} # Printing dictionary before removal print ("The dictionary before performing remove is : " + str(netflix_dict)) # Using del to remove a dict # removes You del netflix_dict['You'] # Printing dictionary after removal print ("The dictionary after remove is : " + str(netflix_dict))
Output
python3 app.py The dictionary before performing remove is : {'Staranger Things': 11, 'You': 3, 'BoJack Horseman': 21} The dictionary after remove is : {'Staranger Things': 11, 'BoJack Horseman': 21}
In the above program, we have removed the element whose key is “You” using the del operator.
Let’s see another scenario where the key does not exist in the dictionary and then try to remove the element.
# app.py netflix_dict = {"Stranger Things" : 11, "You" : 3, "BoJack Horseman" : 21} # Printing dictionary before removal print ("The dictionary before performing remove is : " + str(netflix_dict)) # Using del to remove a dict # try to removes Black Mirror del netflix_dict['Black Mirror'] # Printing dictionary after removal print ("The dictionary after remove is : " + str(netflix_dict))
Output
python3 app.py The dictionary before performing remove is : {'Staranger Things': 11, 'You': 3, 'BoJack Horseman': 21} Traceback (most recent call last): File "app.py", line 8, in <module> del netflix_dict['Black Mirror'] KeyError: 'Black Mirror'
So, we got the KeyError because of the key “Black Mirror” which does not exist in the dictionary.
Deleting a key from a dictionary using del and try/except
We can use try/except mechanism handling if the key is not found, then we catch the exception and show the proper error to the user.
See the following code.
# app.py netflix_dict = {"Stranger Things" : 11, "You" : 3, "BoJack Horseman" : 21} # Printing dictionary before removal print ("The dictionary before performing remove is : " + str(netflix_dict)) try: del netflix_dict['Black Mirror'] except KeyError: print("Key 'Black Mirror' not found") # Printing dictionary after removal print ("The dictionary after remove is : " + str(netflix_dict))
Output
python3 app.py The dictionary before performing remove is : {'Staranger Things': 11, 'You': 3, 'BoJack Horseman': 21} Key 'Black Mirror' not found The dictionary after remove is : {'Staranger Things': 11, 'You': 3, 'BoJack Horseman': 21}
In the above code, we have written the del code inside the try block, and if the key is not found, it throws an exception, and we expect that exception and display the proper error to the user.
One thing to note is that the execution of the program did not stop; it continues.
Removing a key from the dictionary using dict.pop()
If the key exists in the dictionary, then the dict.pop() removes the item with a given key from the dictionary and returns its value.
If the given key doesn’t exist in the dictionary, it returns the given Default value.
If the given key doesn’t exist in the dictionary and the No Default value is passed to pop(), it will throw the KeyError.
See the following code.
# app.py netflix_dict = {"Stranger Things" : 11, "You" : 3, "BoJack Horseman" : 21} # Printing dictionary before removal print ("The dictionary before performing remove is : " + str(netflix_dict)) # Using dict.pop() method to remove a dict # removes You netflix_dict.pop('You') # Printing dictionary after removal print ("The dictionary after remove is : " + str(netflix_dict))
Output
python3 app.py The dictionary before performing remove is : {'Stranger Things': 11, 'You': 3, 'BoJack Horseman': 21} The dictionary after remove is : {'Stranger Things': 11, 'BoJack Horseman': 21}
In the above code, we have passed the You as a key parameter to remove that element from the dictionary.
Let’s delete an element not present in the dictionary using pop().
# app.py netflix_dict = {"Stranger Things" : 11, "You" : 3, "BoJack Horseman" : 21} # Printing dictionary before removal print ("The dictionary before performing remove is : " + str(netflix_dict)) # Using dict.pop() method to remove a dict # removes You netflix_dict.pop('Black Mirror') # Printing dictionary after removal print ("The dictionary after remove is : " + str(netflix_dict))
Output
python3 app.py The dictionary before performing remove is : {'Stranger Things': 11, 'You': 3, 'BoJack Horseman': 21} Traceback (most recent call last): File "app.py", line 8, in <module> netflix_dict.pop('Black Mirror') KeyError: 'Black Mirror'
So, as expected, it gives the KeyError.
Now, let’s pass the default value in the dict.pop() function’s argument and see the output.
# app.py netflix_dict = {"Stranger Things": 11, "You": 3, "BoJack Horseman": 21} # Printing dictionary before removal print("The dictionary before performing remove is : " + str(netflix_dict)) # Using dict.pop() method to remove a dict # removes You removed_item = netflix_dict.pop('Black Mirror', 'Not found') # Printing dictionary after removal print(removed_item)
Output
python3 app.py The dictionary before performing remove is : {'Stranger Things': 11, 'You': 3, 'BoJack Horseman': 21} Not found
In the above code, we passed the default value, “Not found“. So, the return value from the function dict.pop() would be ‘Not found’.
Deleting a key from the dictionary using pop() and try/except
Let’s use try/except mechanism to handle the exception.
# app.py netflix_dict = {"Stranger Things": 11, "You": 3, "BoJack Horseman": 21} # Printing dictionary before removal print("The dictionary before performing remove is : " + str(netflix_dict)) # Using dict.pop() method to remove a dict # removes You try: removed_item = netflix_dict.pop('Black Mirror', 'Not found') except KeyError: print("Key 'Black Mirror' not found") # Printing dictionary after removal print(removed_item)
Output
python3 app.py The dictionary before performing remove is: {'Stranger Things': 11, 'You': 3, 'BoJack Horseman': 21} Not found
Conclusion
We can remove dictionary items or keys in Python using different approaches like using a del statement or using dict.pop() method.
That’s it.