How can I remove a key from a Python dictionary?

You can use the del statement to remove a key-value pair from a dictionary in Python. Here is an example:

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

del my_dict['b']

print(my_dict)  # {'a': 1, 'c': 3}

Watch a course Python - The Practical Guide

Alternatively, you can use the pop() method to remove a key-value pair from the dictionary and return the value. This is useful if you want to retrieve the value before deleting the key. Here is an example:

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

value = my_dict.pop('b')

print(value)  # 2
print(my_dict)  # {'a': 1, 'c': 3}

The pop() method also takes an optional second argument, which is the default value to return if the key is not found in the dictionary. This can be useful to avoid KeyError exceptions.

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

value = my_dict.pop('d', 'not found')

print(value)  # 'not found'
print(my_dict)  # {'a': 1, 'b': 2, 'c': 3}