How can I remove a key from a dictionary in Python?
Antek N
antek n profile pic

In Python, you can remove a key-value pair from a dictionary using thedel statement or thepop() method. Here's a detailed explanation of both methods: Using thedel statement: Thedel statement is used to remove an item from a dictionary by specifying the key to be deleted.

1
2
3
4
5
6

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

del my_dict['b']

print(my_dict)

In this example,del my_dict['b'] removes the key-value pair with the key'b' from themy_dict dictionary. After deletion, the dictionary is modified and the updated contents are displayed using theprint() statement. It's important to note that usingdel with a non-existent key will raise aKeyError. To avoid this, you can first check if the key exists using thein operator or theget() method. Using thepop() method: Thepop() method is used to remove a key-value pair from a dictionary and return the corresponding value.

1
2
3
4
5
6
7

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

removed_value = my_dict.pop('b')

print(my_dict)
print(removed_value)

In this example,my_dict.pop('b') removes the key-value pair with the key'b' from themy_dict dictionary and returns the value associated with it. The dictionary is modified, and the updated contents are displayed using the firstprint() statement. The removed value is assigned to the variableremoved_value and displayed using the secondprint() statement. Similar todel, usingpop() with a non-existent key will raise aKeyError. However, you can provide a default value as the second argument topop() to avoid this. If the key doesn't exist, the default value will be returned instead of raising an error. Choose the method that best suits your needs based on whether you need to retrieve the value associated with the key or if you simply want to remove the key-value pair.