How to Remove Element from Python Dictionary?

By Hardik Savani October 30, 2023 Category : Python

Hello Dev,

In this quick guide, we will teach you how to remove element from dictionary in python. We will look at an example of python remove element from dictionary. I would like to share with you how to remove element from python dictionary. If you have a question about how to remove element from dict python then I will give a simple example with a solution.

There are several ways to remove elements from a dictionary in python. i will give you four examples using pop(), popitem(), del and using value in python.

So, without further ado, let's see simple examples:

Example 1: Python Dictionary Remove Element using pop()

main.py

user = {
  "ID": 1,
  "name": "Hardik Savani",
  "email": "hardik@gmail.com"
}
  
# Remove Item from dictionary
user.pop("email")
  
print(user)

Output:

{
 'ID': 1,
 'name': 'Hardik Savani'
}

Example 2: Python Dictionary Remove Element using popitem()

main.py

user = {
  "ID": 1,
  "name": "Hardik Savani",
  "email": "hardik@gmail.com"
}
  
# Remove Item from dictionary
user.popitem()
  
print(user)

Output:

{
 'ID': 1,
 'name': 'Hardik Savani'
}

Example 3: Python Dictionary Remove Element using del

main.py

user = {
  "ID": 1,
  "name": "Hardik Savani",
  "email": "hardik@gmail.com"
}
  
# Remove Item from dictionary
del user["email"]
  
print(user)

Output:

{
 'ID': 1,
 'name': 'Hardik Savani'
}

Example 4: Python Dictionary Remove Element using value

main.py

user = {
  "ID": 1,
  "name": "Hardik Savani",
  "email": "hardik@gmail.com"
}
  
# Remove Item from dictionary
user = {key:val for key, val in user.items() if val != "hardik@gmail.com"}
  
print(user)

Output:

{
 'ID': 1,
 'name': 'Hardik Savani'
}

I hope it can help you...

Tags :
Shares