remove a key-value pair from a map in python

To remove a key-value pair from a dictionary (which is the equivalent of a map in Python), you can use the del keyword followed by the key you want to remove. Here's an example:

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['a']
print(my_dict)  # Output: {'b': 2, 'c': 3}
95 chars
4 lines

In the above code, the key 'a' and its corresponding value 1 is removed from the my_dict dictionary using the del keyword.

You can also use the pop() method to remove a key-value pair and get the value of the removed key at the same time:

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('a')
print(my_dict)  # Output: {'b': 2, 'c': 3}
print(value)  # Output: 1
129 chars
5 lines

In the above code, the key 'a' and its corresponding value 1 is removed from the my_dict dictionary using the pop() method and the value is stored in the value variable.

related categories

gistlibby LogSnag