Delete an Element in a Dictionary | Python

Rate this post

Summary: Use these methods to delete a dictionary element in Python –
(1) del dict[‘key’]
(2) dict.clear(‘key’)
(3) Use a dictionary comprehension
(4) Use a for loop to eliminate the key

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 Dictionaries

A Python dictionary is a data structure that is used to store data in the key-value pairs. A Python dictionary –

  • is mutable
  • doesn’t allow duplicate keys
  • ordered (since Pthon 3.7). Prior to that dictionaries are unordered.

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 Walkthrough

Method 1: Using “del” Keyword

Approach: The del keyword along with the specified key allows us to remove elements from a dictionary.

Code:

d = {
    'model': 'iPhone 13',
    'weight': '173 grams',
    'display': '6.1"'
}
del d['display']
print(d)

Output:

{'model': 'iPhone 13', 'weight': '173 grams'}

A drawback of using the del keyword is that it can lead to the occurence of an error if the key is not present in the dictionary. In order to handle this situation, you can use the try-except blocks. Here’s an example that demonstrates this scenario:

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:

One or more keys were not found. Use proper key to delete an element!
{'model': 'iPhone 13', 'weight': '173 grams'}

Method 2: Using pop

Approach: The pop() method is used to remove an element from the dictionary with the specified key name.

Code:

d = {
    'model': 'iPhone 13',
    'weight': '173 grams',
    'display': '6.1"'
}
# removing element display from the dictionary
d.pop('display')
print(d)

Output:

{'model': 'iPhone 13', 'weight': '173 grams'}

Python “popitem()” Method

Since Python dictionaries are now ordered ( from Python 3.7 and above), you can use the dict.popitem() method to remove the last inserted item from a dictionary.

Code:

d = {
    'model': 'iPhone 13',
    'weight': '173 grams',
    'display': '6.1"'
}
# removing the last element from the dictionary
d.popitem()
print(d)

Output:

{'model': 'iPhone 13', 'weight': '173 grams'}

Explanation: Since the last item in this dictionary was 'display': '6.1", it will be removed first when the popitem() method is used once.

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 <module>
    d.pop('color')
KeyError: 'color

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 Comprehension

Approach: 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:

{'model': 'iPhone 13', 'weight': '173 grams'}

Method 4: Iterating and Eliminating

Approach: Another way to remove an element from the dictionary is to use a three step process.
Step 1: Store the contents from original dictionary to a temporary dictionary.
Step 2: Empty the original dictionary.
Step 3: Iterate across the temporary dictionary and store only the required elements in the emptied original dictionary. Do not store the key-value pair that you want to remove.

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:

{'model': 'iPhone 13', 'weight': '173 grams'}

How to Delete all Keys from a Dictionary?

Method 1: Using dict.clear()

dict.clear() is a dictionary method that allows us to remove all elements of a dictionary and empties the dictionary.

d = {
    'model': 'iPhone 13',
    'weight': '173 grams',
    'display': '6.1"'
}
d.clear()
print(len(d))

# OUTPUT: 0

Method 2: Using del

You can also opt to delete an entire dictionary with the help of the del keyword as shown below:

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

clear()del
Removes all key-value pairs from the dictionary and returns an empty dictionary.Deletes the dictionary completely, i.e., no trace of the dictionary remains once you delete it using the del method.
EXAMPLE:
d = {
‘model’: ‘iPhone 13’,
‘weight’: ‘173 grams’,
‘display’: ‘6.1″‘
}
d.clear()
print(len(d))

# Output: 0
EXAMPLE:
d = {
‘model’: ‘iPhone 13’,
‘weight’: ‘173 grams’,
‘display’: ‘6.1″‘
}
del d
print(len(d))

# ouput: NameError: name ‘d’ is not defined

Recommended Read: How to Check if a Key Exists in a Python Dictionary?

Conclusion

We 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
(1)
Python Dictionary: How to Create, Add, Replace, Retrieve, Remove
(2) Python Dictionary clear()


Finxter Computer Science Academy

  • One of the most sought-after skills on Fiverr and Upwork is web scraping. Make no mistake: extracting data programmatically from websites is a critical life skill in today’s world that’s shaped by the web and remote work.
  • So, do you want to master the art of web scraping using Python’s BeautifulSoup?
  • If the answer is yes – this course will take you from beginner to expert in Web Scraping.