How to remove key from dictionary in Python

Published on Aug. 22, 2023, 12:16 p.m.

In Python, you can remove a key from a dictionary using the del statement or the pop() method. Here are some examples:

Using del:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
del my_dict["key2"]
print(my_dict)

In this example, the del statement is used to remove the key-value pair with key "key2" from the dictionary my_dict. The output will be 'key1': 'value1', 'key3': 'value3' (since the key-value pair with key "key2" has been deleted).

Using pop():

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
my_dict.pop("key2")
print(my_dict)

In this example, the pop() method is used to remove the key-value pair with key "key2" from the dictionary my_dict. The output will again be 'key1': 'value1', 'key3': 'value3'.

Note that if you try to remove a key that does not exist in the dictionary, both del and pop() will raise a KeyError. To avoid this, you can use the optional second argument of pop(), which specifies a default value to return if the key is not found:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
my_dict.pop("key4", None)  # will not raise an error

In this example, the pop() method is used with a default value of None, which will be returned if the key "key4" is not found in the dictionary.

Tags: