Python Example Delete an element from Dictionary Example

This tutorial explains How to delete keys and values from a dictionary

Python Dict delete example

There are multiple ways we can remove an element from a dictionary

  • using del statement

The del statement removes a key and value pair by giving a key

Syntax

del dict[key]
  • if the key is found in the dictionary, delete the key and value from it.
  • if the key is not found, It raises an error KeyError.
  • handle this error using the condition try and except

This does not return anything.

emp={ 'id': 1, 'name': 'john','dept': 'sales', 'role': 'sales', 'salary': 4000}
print(emp)

del emp['salary']
print(emp)

Output:

{'id': 1, 'name': 'john', 'dept': 'sales', 'role': 'sales', 'salary': 4000}
{'id': 1, 'name': 'john', 'dept': 'sales', 'role': 'sales'}

If the key does not exist, It raises a KeyError: error

emp={ 'id': 1, 'name': 'john','dept': 'sales', 'role': 'sales', 'salary': 4000}
print(emp)

del emp['salary1']
print(emp) #KeyError: 'salary1'

To handle this

One way is used to handle errors using try and except

The KeyError handle and code do not break its execution, instead, it prints the key does not exist message.

emp={ 'id': 1, 'name': 'john','dept': 'sales', 'role': 'sales', 'salary': 4000}
print(emp)
key='salary1';
try:
    del emp[key]
except KeyError as ex:
    print("Key not exists: ",key )

Another way using if conditional check

Check key exists in the Dictionary using the if key in dictionary condition, and delete from the dictionary if the condition is satisfied.

emp={ 'id': 1, 'name': 'john','dept': 'sales', 'role': 'sales', 'salary': 4000}
print(emp)
key='salary1';
if key in emp:
    del emp[key]

  • using pop statement

pop function in a dictionary removes an element and returns the value for a dictionary.

Syntax

dict.pop(key)
  • if the key is found in the dictionary, delete the key and value, and return the value.
  • if the key is not found, It raises an error KeyError.
  • handle this error using if condition and try and except
emp={ 'id': 1, 'name': 'john','dept': 'sales', 'role': 'sales', 'salary': 4000}
print(emp)
key='salary';
print(emp.pop(key))
print(emp)

Here is an example to handle key not found errors

emp={ 'id': 1, 'name': 'john','dept': 'sales', 'role': 'sales', 'salary': 4000}
print(emp)
key='salary1';
# If condition
if key in emp:
    del emp[key]
# Try and except
try:
    del emp[key]
except KeyError as ex:
    print("Key not exists: ",key )