Python - Remove a Dictionary Key

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')
print(removed_item)
# 1

print(my_dict)
# {'b': 2, 'c': 3}

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

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

print(my_dict)
# {'c', 3}

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