How do you delete and remove an element from a dictionary Python?
[toc] Show
Summary: Use these methods to delete a dictionary element in Python – Problem: Given a Python dictionary. How to delete an element from the dictionary? Example: d = { 'model': 'iPhone 13', 'weight': '173 grams', 'display': '6.1"' } # SOME METHOD TO DELETE THE DISPLAY ELEMENT FROM THE DICTIONARY print(d) # EXPECTED OUTPUT: {'model': 'iPhone 13', 'weight': '173 grams'} A Quick Recap to Python DictionariesA Python dictionary is a data structure that is used to store data in the key-value pairs. A Python dictionary –
Note: Since Python 3.7, dictionaries are ordered. However, in Python3.6 and earlier, dictionaries are unordered. Well, that should have been a good refresher to Python dictionaries. Now, let us dive into our mission-critical question – “How to delete an element from a Python dictionary?” There are several ways of removing elements from a dictionary. Let’s go through each method. Video WalkthroughDelete an Element in a Dictionary | Python Method 1: Using “del” KeywordApproach: The Code: d = { 'model': 'iPhone 13', 'weight': '173 grams', 'display': '6.1"' } del d['display'] print(d) Output:
A drawback of using the d = { 'model': 'iPhone 13', 'weight': '173 grams', 'display': '6.1"' } try: del d['display'] del d['color'] except: print("One or more keys were not found. Use proper key to delete an element!") print(d) Output:
Method 2: Using popApproach: The Code: d = { 'model': 'iPhone 13', 'weight': '173 grams', 'display': '6.1"' } # removing element display from the dictionary d.pop('display') print(d) Output:
Python “popitem()” MethodSince Python dictionaries are now ordered ( from Python 3.7 and above), you can use the Code: d = { 'model': 'iPhone 13', 'weight': '173 grams', 'display': '6.1"' } # removing the last element from the dictionary d.popitem() print(d) Output:
Explanation: Since the last item in this dictionary was
What happens if you attempt to Pop a Key from a Dictionary and the Key does not exist?If you try to pop a key from the dictionary that does not exist then it will raise an error as shown below. d = { 'model': 'iPhone 13', 'weight': '173 grams', 'display': '6.1"' } d.pop('color') print(d) Output: Traceback (most recent call last): File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxter\General\delete_dictionary_element.py", line 6, in Solution: To eliminate/handle this error you must use the try-except blocks. d = { 'model': 'iPhone 13', 'weight': '173 grams', 'display': '6.1"' } try: d.pop('color') print(d) except: print('You are trying to remove wrong key!') Method 3: Using Dictionary ComprehensionApproach: A workaround to delete an element from a dictionary is to iterate across all the keys in the dictionary except the one that you want to delete using a dictionary comprehension and then store only the required keys in the dictionary. Code: d = { 'model': 'iPhone 13', 'weight': '173 grams', 'display': '6.1"' } # dictionary comprehension that eliminates 'display' key d = {i: d[i] for i in d if i != 'display'} print(d) Output:
Method 4: Iterating and EliminatingApproach: Another way to remove an element from the dictionary is to use a three step process. Code: d = { 'model': 'iPhone 13', 'weight': '173 grams', 'display': '6.1"' } # store d in temp temp = d # empty the dictionary d d = {} # eliminate the unrequired element and restore other elements for key, value in temp.items(): if key != 'display': d[key] = value print(d) Output:
How to Delete all Keys from a Dictionary?Method 1: Using dict.clear()
d = { 'model': 'iPhone 13', 'weight': '173 grams', 'display': '6.1"' } d.clear() print(len(d)) # OUTPUT: 0 Method 2: Using delYou can also opt to delete an entire dictionary with the help of the d = { 'model': 'iPhone 13', 'weight': '173 grams', 'display': '6.1"' } del d try: print(d) except: print('Dictionary has been deleted!') # OUTPUT: Dictionary has been deleted! Difference between Clear() and Del statement
Recommended Read: How to Check if a Key Exists in a Python Dictionary? ConclusionWe have come to the end of this comprehensive tutorial on how to remove an element from the dictionary. I hope it has answered your queries. Please join us to learn new concepts every day. Recommended Reads Finxter Computer Science Academy
I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking. You can contact me @:
UpWork Can we delete elements from dictionary?You can use both dict. pop() method and a more generic del statement to remove items from a dictionary. They both mutate the original dictionary, so you need to make a copy (see details below). Unless you use pop() to get the value of a key being removed you may provide anything, not necessary None .
Can you remove a key from a dictionary Python?Use Python del to Remove a Key from a Dictionary
Python also provides the del keyword to remove a key from a dictionary. Using the del keyword is a less safe approach, as there is not way to simply provide a default_value , as you can with the . pop() method.
What is dictionary add and remove element from dictionary?Removing elements from Dictionary
We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value . The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary.
|