Remove key from dictionary in Python [Practical Examples]

Different ways to remove key from dictionary in Python

In Python, Dictionary is a mutable object that stores the record in the form of key-value pair. So, we can anytime update the value or delete a key value pair from dictionary if they are no longer in use.

Suppose, if we have a Python dictionary to store the record of a student including the personal details like studentid(sid), name, age, department(dept), location, rank, publications and projects. At some point of time, we may decide to remove the details of projects or ranks for a student. In this case, we have several ways to remove key from dictionary as listed below.

Advertisement
  • Using pop() method
  • Using popitem() method
  • Using del() method
  • Using items() method and looping
  • Using clear() method
  • Using Comprehension method

 

Method-1: Using pop() method

The Python pop() method removes a key from a dictionary. This method accepts two parameters, first parameter as a key to delete and second parameter is a optional value that will be returned if the key do not exist. However, if you fail to specify the second parameter and if the key do not exist then the interpreter will throw a KeyError.

Example : In this example, we will pop the key value pair with the name of key as "projects".

# Python script to remove key from dictionary
# Initializing
Student = {'sid':22146,'name': 'Jim', 'age': '19', 'dept':'Comp',"location":"Mumbai","rank":15874,"publications":5,"projects":2}
print("Before removal ",Student)

# Remove key value pair using pop method
Student.pop("projects")

# Printing 
print("After removal ",Student)

Output

Before removal  {'sid': 22146, 'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 5, 'projects': 2}
After removal  {'sid': 22146, 'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 5}

 

Method-2: Using popitem() method

The popitem() method removes the item that was last inserted into the dictionary. In versions before 3.7, the popitem() method removes a random item. Moreover, the removed item is the returned as a tuple.

Example : In this example, the popitem() method will return the last key value pair inserted in the dictionary.

# Python script to remove key from dictionary
# Initializing
Student = {'sid':22146,'name': 'Jim', 'age': '19', 'dept':'Comp',"location":"Mumbai","rank":15874,"publications":5,"projects":2}

# Adding one more key value pair
Student.update({"Year":2021})

print("Before removal ",Student)

# Remove key value pair using pop method
Student.popitem()

# Printing 
print("After removal ",Student)

Output

Advertisement
Before removal  {'sid': 22146, 'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 5, 'projects': 2}
After removal  {'sid': 22146, 'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 5, 'projects': 2}

 

Method-3: Using del keyword

The del keyword is used to delete an objects. As we know, that everything is an object in Python, so we can use the del keyword to delete keys of a dictionary.

Example : In this example, we will remove the key value pair using the del keyword.

# Python script to remove key from dictionary
# Initializing
Student = {'sid':22146,'name': 'Jim', 'age': '19', 'dept':'Comp',"location":"Mumbai","rank":15874,"publications":5,"projects":2}

print("Before removal ",Student)

# Remove key value pair using del keyword
del(Student['rank'])

# Printing 
print("After removal ",Student)

Output

Before removal  {'sid': 22146, 'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 5, 'projects': 2}
After removal  {'sid': 22146, 'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'publications': 5, 'projects': 2}

 

Method-4: Using items() method and looping

In this approach, we will create a new dictionary and copy the content from student to the new one such that a keytodelete will not be copied. Here, we will use items method to iterate over the dictionary.

Example : In this example, we will remove the desired key value pair by iterating over the dictionary using the items method.

# Python script to remove key from dictionary
# Initializing
Student = {'sid':22146,'name': 'Jim', 'age': '19', 'dept':'Comp',"location":"Mumbai","rank":15874,"publications":5,"projects":2}

print("Before removal ",Student)

keytodelete="rank"

# Creating a new empty dictionary
d={}

# Copy all the key value pair except the one given in keytodelete
for key, value in Student.items():
    if key is not keytodelete:
        d[key] = value

# Printing 
print("The new dictionary is ",d)

Output

Before removal {'sid': 22146, 'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 5, 'projects': 2}
The new dictionary is {'sid': 22146, 'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'publications': 5, 'projects': 2}

 

Method-5: Using clear() method

We can use the clear() method, if we want to delete all the keys from a dictionary.

Example : In this example, clear an entire dictionary items.

# Python script to remove key from dictionary
# Initializing
Student = {'sid':'','name': 'Jim', 'age': '19', 'dept':'Comp',"location":"Mumbai","rank":15874,"publications":5,"projects":2}

print("Before removal",Student)
Student.clear()

# Printing 
print("After removal",Student)

Output

Before Pop {'sid': '', 'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 5, 'projects': 2}
After Pop {}

 

Method-6: Using comprehension method

In this approach, we are using the dict comprehension and items() method to remove key from dictionary.

The items() method always returns an object of the dictionary. So, the object is a collection of key-value tuples. Here, Dict comprehension will be used for creating a dictionary by including all the key-value pairs except the one to delete. Note that here also new dictionary will be created whereas the content of the original dictionary remains unchanged.

Example : In this example, we will use dict comprehension and items() method to remove key from a dictionary.

# Python script to remove key from dictionary
# Initializing
Student = {'sid':'','name': 'Jim', 'age': '19', 'dept':'Comp',"location":"Mumbai","rank":15874,"publications":5,"projects":2}

print("Before removal ",Student)

d = {k:v for k, v in Student.items() if v!= ''}

print ("After removal ",(d))

Output

Before removal  {'sid': '', 'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 5, 'projects': 2}
After removal  {'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 5, 'projects': 2}

 

Examples of removing one or more keys from Python Dictionary

Remove empty value keys

In many situations, we may need to find all the keys whose value does not exist. Thereafter, we have to delete such a key one by one. The code below will remove key from dictionary whose value does not exists.

Example :

# Initializing
Student = {'sid':'','name': 'Jim', 'age': '19', 'dept':'Comp',"location":"Mumbai","rank":15874,"publications":5,"projects":2}

print("Before removal ",Student)

# Creating a new empty dictionary
d={}
valuetodelete=''
# Copy all the key value pair except the one that matches the value of valuetodelete
for key, value in Student.items():
    if value is not valuetodelete:
        d[key] = value

# Printing 
print("The new dictionary is ",d)

Output

Before removal  {'sid': '', 'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 5, 'projects': 2}
The new dictionary is  {'name': 'Jim', 'age': '19', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 5, 'projects': 2}

 

Remove duplicate keys

In this example, we will remove the key value pair that has the same value as the other one by using the loop and items() method. Firstly, we will initialize a dictionary and remove duplicate keys in a dictionary using loops, this method will remove any duplicate values from our dictionary.

Example :

# Initializing
Student = {'sid':'19','name': 'Jim', 'age': '19', 'dept':'Comp',"location":"Mumbai","rank":15874,"publications":5,"projects":2}

newkey = []
d = dict()
for k, v in Student.items():
    if v not in newkey:
        newkey.append(v)
        d[k] = v
  
print("After Removal ",d)

Output

After Removal {'sid': '19', 'name': 'Jim', 'dept': 'Comp', 'location': 'Mumbai', 'rank': 15874, 'publications': 19, 'projects': 2}

 

Summary

The knowledge of removing a key from dictionary in python is very useful while working on real time applications. In many situations, we will need to delete the unwanted key value pairs from dictionary. In this tutorial, we covered the six different ways to remove key from dictionary. We learned in detail about this with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on removing a key from dictionary in Python.

 

References

Dictionaries in Python

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X