3 Easy Ways to Remove Key from Dictionary in Python

Three ways to remove a key from the Python Dictionary:

  1. Use dict.pop() method
  2. Using del keyword.
  3. Delete the key from the dictionary using del and try/except.

Using dictionary pop() method

Python dictionary pop() is a built-in method that removes a key from the dictionary. The pop() method accepts a key argument and deletes that key-value element.

For example, the dict pop() method removes and returns an item from a dictionary provided with the given key. 

If the key exists in the dictionary, then dict.pop() removes the element with the given key from the dictionary and returns its value.

If the given key doesn’t exist in the dictionary, it returns the given Default value. If the given key doesn’t exist in the dictionary and the No Default value is passed to pop(), it will throw KeyError.

See the following code.

# app.py

adict = {'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
print(adict)
rEl = adict.pop('c')
print(adict)
print('Removed element: ', rEl)

Output

python3 app.py
{'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
{'a': 'abel', 'b': 'billie', 'd': 'delray'}
Removed element:  cyrus

The dict.pop() method returns the removed element.

Removing the key from the dictionary using the del keyword

Python del keyword removes one or more elements from a collection.

The del works on lists and dictionaries.

See the following syntax.

del d[key]

The del statement removes the given item from the dictionary. If the given key is not in the dictionary, it will throw KeyError.

See the following code.

adict = {'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
print(adict)
if "c" in adict:
    del adict["c"]

print("Updated Dictionary :", adict)

Output

python3 app.py
{'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
Updated Dictionary : {'a': 'abel', 'b': 'billie', 'd': 'delray'}

Del is a clear and fast way to delete elements from the dictionary.

Removing the key from the dictionary using del and try/except

# app.py

adict = {'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
print(adict)
key = "e"
try:
    del adict[key]
except KeyError:
    print(f'Key {key} not found')

print("Updated Dictionary :", adict)

Output

python3 app.py
{'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}
Key e not found
Updated Dictionary : {'a': 'abel', 'b': 'billie', 'c': 'cyrus', 'd': 'delray'}

In the above program, we try to delete a key that does not exist in the dictionary and catch the error.

Conclusion

There are more than one standard ways to remove keys from a dictionary in Python. For example, you can use del, dict.pop() method to remove an element.

See also

Python dictionary update()

Python dictionary values()

Python dictionary popItem()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.