Skip to main content

How to remove key-value pairs from a dictionary in Python

How to remove key-value pairs from a dictionary in Python.

Here is a detailed step-by-step tutorial on how to remove key-value pairs from a dictionary in Python.

Step 1: Create a dictionary

First, we need to create a dictionary to work with. A dictionary in Python is a collection of key-value pairs enclosed in curly braces.

my_dict = {'apple': 5, 'banana': 2, 'orange': 3, 'grape': 4}

In this example, we have a dictionary called my_dict with four key-value pairs.

Step 2: Using del keyword

The del keyword in Python is used to delete items from a dictionary. To remove a specific key-value pair, we can use the del keyword followed by the key we want to delete.

del my_dict['banana']

After executing this line of code, the key-value pair with the key 'banana' will be removed from the dictionary.

Step 3: Using pop() method

Another way to remove a key-value pair from a dictionary is by using the pop() method. This method removes the specified key and returns its corresponding value.

my_dict.pop('orange')

After executing this line of code, the key-value pair with the key 'orange' will be removed from the dictionary, and the value '3' will be returned.

Step 4: Removing the last added key-value pair using popitem() method

If you want to remove the last added key-value pair from a dictionary, you can use the popitem() method. This method removes and returns the key-value pair that was last inserted into the dictionary.

my_dict.popitem()

After executing this line of code, the last added key-value pair, in this case, 'grape': 4, will be removed from the dictionary.

Step 5: Removing all key-value pairs from the dictionary

To remove all key-value pairs from a dictionary, we can use the clear() method. This method removes all items from the dictionary, leaving it empty.

my_dict.clear()

After executing this line of code, the dictionary my_dict will be empty.

Step 6: Using a loop to remove multiple key-value pairs

If you want to remove multiple key-value pairs from a dictionary, you can use a loop. You can iterate over a list of keys and remove them one by one.

keys_to_remove = ['apple', 'banana', 'orange']
for key in keys_to_remove:
if key in my_dict:
del my_dict[key]

In this example, we have a list called keys_to_remove containing the keys 'apple', 'banana', and 'orange'. The loop iterates over each key, checks if it exists in the dictionary, and deletes it if found.

That's it! You now know different ways to remove key-value pairs from a dictionary in Python. Feel free to experiment and use the method that best suits your needs.