Python Dictionary Delete Item by Key Example

By Hardik Savani October 30, 2023 Category : Python

Hi Friends,

This is a short guide on python dictionary remove item by key. We will look at an example of python dictionary delete item by key. Here you will learn python remove items from dictionary by key. We will look at an example of python dictionary remove item by index. Alright, let us dive into the details.

There are several ways to remove element by index from a dictionary in python. i will give you four examples using pop() and del 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 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'
}

I hope it can help you...

Tags :
Shares