How to Remove Element from Python Dictionary?
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Add Element in Dictionary Python?
- How to Add Item in Dictionary Python?
- Python Create JSON File from Dict Example
- How to Check If a List is Empty or Not in Python?
- Python Read Text File into List Example
- How to Add Element to a List in Python?
- Python List Print All Elements Except First Example
- Python List Print All Elements Except Last Example
- How to Get Min Value from Python List?
- How to Get Max Value from Python List?
- How to Convert List to Uppercase in Python?
- Python Split String into List of Characters Example