Python - Remove a Dictionary Key

1 min read

There are two ways to remove a key from a dictionary in Python. You can use the dictionary's pop() method which will return the value of the key that was removed or you can use the del keyword which is slightly faster. However, the disadvantage of using the del keyword is that Python will raise a KeyError if the key you are attempting to delete does not exist whereas with the pop() method you can pass None as the second argument and it will return this value and not raise a KeyError if the key is not found. Here are some examples:

my_dict = {'a': 1, 'b': 2, 'c': 3}

# Pop the 'a' key and return its value to removed
removed_item = my_dict.pop('a')
# 1

# {'b': 2, 'c': 3}

# Pop non-existent 'a' key
retry = my_dict.pop('a', None)
# None

# Delete the 'b' key
del my_dict['b']

# {'c', 3}

# Try to delete non-existent 'b'
del my_dict['b']
# KeyError: 'b'

Author picture
Rhett Trickett

Founder at Able

@rhett RhettTrickett rhetttrickett

Join the discussion

Able is a developer community where people build their coding knowledge and careers.

Join with GitHub Join with Twitter