Remove Element from Python Dictionary Tutorial Example

28-Jan-2023

.

Admin

Remove Element from Python Dictionary Tutorial Example

Hi Dev,

I will explain step by step tutorial Remove Element from Python Dictionary Tutorial Example. I’m going to show you about how to remove from python dictionary. you'll learn how to remove entry from dictionary python. it's simple example of how to remove item from dict python.

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

Example 1: Python Dictionary Remove Item using pop()


main.py

user = {

"ID": 1,

"name": "Piyush Kamani",

"email": "piyush@gmail.com"

}

# Remove Item from dictionary

user.pop("email")

print(user)

Output:

{

'ID': 1,

'name': 'Piyush Kamani'

}

Example 2: Python Dictionary Remove Item using popitem()

main.py

user = {

"ID": 1,

"name": "Piyush Kamani",

"email": "piyush@gmail.com"

}

# Remove Item from dictionary

user.popitem()

print(user)

Output:

{

'ID': 1,

'name': 'Piyush Kamani'

}

Example 3: Python Dictionary Remove Item using del

main.py

user = {

"ID": 1,

"name": "Piyush Kamani",

"email": "piyush@gmail.com"

}

# Remove Item from dictionary

del user["email"]

print(user)

Output:

{

'ID': 1,

'name': 'Piyush Kamani'

}

Example 4: Python Dictionary Remove Item using value

main.py

user = {

"ID": 1,

"name": "Piyush Kamani",

"email": "piyush@gmail.com"

}

# Remove Item from dictionary

user = {key:val for key, val in user.items() if val != "piyush@gmail.com"}

print(user)

Output:

{

'ID': 1,

'name': 'Piyush Kamani'

}

#Python