Remove a key from Dictionary in Python | del vs dict.pop() vs comprehension

How to remove a key from dictionary using del vs dict.pop() vs comprehension in python ?

As we know, Dictionary plays an important role in python data structure.

  • The elements are written with in { }curly brackets, having keys and values.
  • Each key-value pair mapped with the key to its related value.
  • In Dictionaries duplicates are not allowed.
Syntax : mydict = {key1: value1, key2: value2}

In this article, we will discuss about different ways to remove a key from dictionary in python.

Let us assume we have a dictionary with correspondent keys and values:

#dictionary with keys with their correspondent values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}

Now we will see different method to delete an key from dictionary :

Method -1 : Using dict.pop( ) method :

This pop() method is used to delete a key and its value in its place. The advantage over using del is that it provides a mechanism to print the desired value if you try to remove a non-existent spelling. Secondly it also returns the value of the key that is removed as well as performs a simple delete operation.

#Program :

#dictionary test_dict
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
#this key will be deleted
key_to_be_deleted = 'Sagar'
# As 'Sagar' key is present in dictionary, so pop() will delete
# its entry and return its value
result = test_dict.pop(key_to_be_deleted, None)
print("Deleted item's value = ", result)
print("Updated Dictionary :", test_dict)
Output
Deleted item's value = 36
Updated Dictionary : {'Ram': 32, 'Dhruv': 45}

In case the key does not exist :

We use try/except method to avoid error. We know key ‘Soni’ is not in dictionary. So, an error will generate. To avoid error try/except method will be used.

#Program :

#dictionary test_dict
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}

#Deleting key which does not exist i.e Soni
key_to_be_deleted = 'Soni'
try:
    test_dict.pop(key_to_be_deleted)
except KeyError:
    print('That Key is not in the dictionary')
Output :
That is not present in the dictionary

Method-2 : Using items() & for loop :

By using item() method and for loop we will iterate over the dictionary. When the key that will be deleted will be matched then delete that key.

Let’s see a program how it’s implemented.

#Program :

# Dictionary with keys and values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# key that to be deleted
key_to_be_deleted = 'Dhruv'
new_dict = {}
#using for loop 
#Iterate one by one key#If found that key then delete
for key, value in test_dict.items():
 if key is not key_to_be_deleted:
  new_dict[key] = value
test_dict = new_dict
print(test_dict)
Output
{'Ram': 32, 'Dhruv': 45}

Here for deletion we used for loop and We created a new temporary dictionary and then duplicated it for all key-value pairs in the original dictionary. During iteration, we copy the key and value pair into a new temporary dictionary only if the key is not equal to the key to be deleted. Once the duplication finished, we copied the contents of the new temporary dictionary into the original dictionary.

Method-3: Using items() & Dictionary Comprehension :

Utilizing the logic of the above example we use items() & dictionary comprehension.

#Program :

# Dictionary with keys and values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# key that to be deleted
key_to_be_deleted = 'Ram'
test_dict = {key: value for key, value\
                  in test_dict.items()\
                  if key is not key_to_be_deleted}
print(test_dict)
Output:
{'Ram': 32, 'Dhruv': 45}

Method-4: Using del keyword :

We can use the del statement to delete a key-value pair from the dictionary regarding on the key.

Syntax : del dict[key]

Let’s use it-

#Program :

# Dictionary of keys &values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# Deleting an item from dictionary using del
del test_dict['Dhruv']
print(test_dict)
Output:
{'Sagar': 36, 'Ram':32}

In case the key does not exist :
Suppose we want to delete key 'Soni', which does not exist then we can use try-except to avoid any exception.

Let’s see the implementation of it.

#Program :

# Dictionary of keys &values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# If key exist in dictionary then delete it using del.
key_to_be_deleted = 'Soni'
try:
 del test_dict[key_to_be_deleted]
except KeyError:
 print('That key is not present in the dictionary')
Output:
That key is not present in the dictionary

Leave a Comment