Delete an element from a dictionary

To delete an element from a dictionary in Python, you can use the del statement. For 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

You can also use the pop() method to delete an item from a dictionary and return its value. For example:

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

value = my_dict.pop('b')

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

You can also use the pop() method with a default value, in case the key is not found in the dictionary. For example:

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}