2 ways to remove an item from a Python dictionary


In today’s post, we’ll discuss two different ways to remove an item from a Python dictionary, using the key of the item.

For the practice question, we’ll work on a function that accepts a dictionary and a variable-length argument, and deletes items from the dictionary based on the variable-length argument.

Here are some topics we’ll covered in the post:

  • How to remove an item from a Python dictionary
  • How to use the del keyword in Python
  • How to use the pop() method
  • How to check if a key exists in a dictionary
  • What are some differences between the del keyword and the pop() method
  • What is a variable-length argument

Key Concepts

There are two main ways to delete an item from a Python dictionary.

  • We can use the del keyword, or
  • the built-in pop() method

Using the del keyword

The first way is to use the del keyword.

To do that, we access the item using its key and use the del keyword to delete it. The syntax is as follows:

del name_of_dictionary[key_to_delete]

Let’s look at an example:

myDict = {'Aaron': 12, 'Bob': 20, 'Calvin': 15, 'David': 21}

del myDict['Bob']
print(myDict)

Here, we first declare and initialize a dictionary called myDict. Next, we use the del keyword to delete the second item (whose key equals 'Bob') from the dictionary.

Finally, we use the print() function to print the resulting dictionary.

If you run the code above, you’ll get the following output:

{'Aaron': 12, 'Calvin': 15, 'David': 21}

The 'Bob':20 pair is removed from myDict.

Using the pop() method

Besides using the del keyword to remove items from a dictionary, we can use the pop() method. This method is very similar to the del keyword. It uses the key of the item to access the item and delete it.

Let’s look at an example:

myDict = {'Aaron': 12, 'Bob': 20, 'Calvin': 15, 'David': 21}

myDict.pop('Bob')
print(myDict)

If you run the code above, you’ll get the following output:

{'Aaron': 12, 'Calvin': 15, 'David': 21}

'Bob':20 is deleted from myDict.

What happens if the key does not exist in the dictionary

Both the del keyword and pop() method throws a KeyError exception if the key we are trying to delete does not exist in the dictionary.

Let’s look at an example:

myDict = {'Aaron': 12, 'Bob': 20, 'Calvin': 15, 'David': 21}
myDict.pop('Barry')
print(myDict)

Here, we try to delete an item from myDict, with ‘Barry’ as the key. Since this key does not exist in myDict, we’ll get an exception as shown below:

Traceback (most recent call last):
  File "...", ..., in <module>
    myDict.pop('Barry')
KeyError: 'Barry'

The same applies if we use the del keyword. If you change line 2 in the code above to

del myDict['Barry']

and rerun the code, you’ll get the same KeyError exception.

If we want to prevent a KeyError exception from occurring, we can check if a key exists in the dictionary before trying to delete the item. To do that, we use the in keyword as shown below:

myDict = {'Aaron': 12, 'Bob': 20, 'Calvin': 15, 'David': 21}

if 'Barry' in myDict:
    del myDict['Barry']

print(myDict)

If you run the code above, you’ll get the following output:

{'Aaron': 12, 'Bob': 20, 'Calvin': 15, 'David': 21}

As ‘Barry’ does not exist in myDict, the if condition on line 3 evaluates to False.

Hence, line 4 is not executed. The program proceeds to line 6 to print out the value of myDict.

Differences between the del keyword and the pop() method

Based on what we’ve covered so far, we can see that the del keyword and the pop() method are very similar. However, there are some key differences between them.

Firstly, the del keyword only deletes items from a dictionary. The pop() method, in contrast, does more than that.

In addition to deleting items from a dictionary, the pop() method also returns the value of the item deleted, which we can store in a variable. Let’s look at an example:

myDict = {'Aaron': 12, 'Bob': 20, 'Calvin': 15, 'David': 21}

deleted = myDict.pop('Bob')
print(myDict)
print(deleted)

If you run the code above, you’ll get the following output:

{'Aaron': 12, 'Calvin': 15, 'David': 21}
20

The 'Bob':20 pair is deleted from myDict. In addition, the pop() method returned the value of the item deleted. Hence, we get 20 when we print the value of deleted.

Next, both the del keyword and pop() method throws an exception by default if the key to be deleted does not exist in the dictionary.

However, with the pop() method, we can prevent the exception from occurring by passing a second argument to the method. This argument allows us to specify a value we want the method to return when the key does not exist.

Let’s look at an example:

myDict = {'Aaron': 12, 'Bob': 20, 'Calvin': 15, 'David': 21}

deleted = myDict.pop('Barry', 'Not found')
print(myDict)
print(deleted)

If you run the code above, you’ll get the following output:

{'Aaron': 12, 'Bob': 20, 'Calvin': 15, 'David': 21}
Not found

As you can see, when we pass the second argument 'Not found' to the pop() method, we do not get an exception when the key to be deleted does not exist. Instead, the method returns the string ‘Not found’. This makes the pop() method slightly easier to use than the del keyword, as we do not need to check if a key exists.

Practice Question

Now that we are familiar with the del keyword and pop() method, let’s move on to the practice question for today.

Today’s practice question requires us to write a function called delKeys() that has two parameters – dic and *keys.

The first parameter stores a dictionary. The second parameter is a variable-length argument that stores the keys to be deleted from dic. We’ll discuss variable-length arguments in the “Additional Notes” section later.

The delKeys() function deletes all items in dic whose keys are found in *keys.

Expected Results

Here’s an example showing how the function should behave:

usernames = {'Max': 5, 'John': 7, 'Miso': 3, 'Noodle': 4, 'Furry': 10}
delKeys(usernames, 'John', 'Alan')
print(usernames)

If you run the code above, you should get the following output:

{'Max': 5, 'Miso': 3, 'Noodle': 4, 'Furry': 10}

The function deleted 'John':7 from the dictionary because we pass 'John' to the function as one of the arguments. Although the last argument 'Alan' does not exist in the dictionary, the function does not give us any error; it simply ignores that argument.

Let’s look at one more example:

pets = {'Ginger': 3, 'Benji': 2, 'Boo': 3, 'XinBa': 1, 'Scooter': 10}
delKeys(pets, 'Benji', 'Ben', 'Lee', 'Scooter')
print(pets)

If you run the code above, you should get the following output:

{'Ginger': 3, 'Boo': 3, 'XinBa': 1}

The function deleted 'Benji':2 and 'Scooter':10 from the pets dictionary.

Additional Notes

What is a variable-length argument

If you study the two examples in the “Expected Results” section above, you may notice something weird. In the first example, we passed three arguments to the delKeys() function. In the second, we passed five.

Recall we mentioned in the “Practice Question” section that delKeys() has a variable-length argument keys?

A variable-length argument is an argument that can store a variable number of values.

To indicate that an argument is a variable-argument, we need to add * in front of its name. In other words, when we define our delKeys() function, we should use the following definition:

def delKeys(dic, *keys)

When we define a function with variable-length arguments, those arguments must come after the non-variable-length arguments (a.k.a. formal arguments). For instance,

def someFunction(a, b, c, *d)

is fine while

def someFunction(*a, b, c, d)

is not (as *a, which is a variable-length argument, comes before the formal arguments).

When we call the delKeys() function using the statement

delKeys(usernames, 'John', 'Alan')

dic = usernames while *keys = 'John', 'Alan'

On the other hand, when we call it using

delKeys(pets, 'Benji', 'Ben', 'Lee', 'Scooter')

dic = pets while *keys = 'Benji', 'Ben', 'Lee', 'Scooter'.

How to access items in a variable-length argument?

To access the items in a variable-length argument, we can use a for loop. Let’s look at an example:

def someFunction(a, b, c, *d):
    print()
    print(a, end='')
    print(b, end='')
    print(c, end='')
    for i in d:
        print(i, end='')

someFunction(1, 2, 3, 'a')
someFunction(1, 2, 3, 'x', 'y', 'z')
someFunction(1, 2, 3, 'p', 'q')

In the example above, *d is a variable-length argument. Inside the function, we use a for loop (lines 6 and 7) to iterate through *d.

If you run the code above, you’ll get the following output:

123a
123xyz
123pq

Now that you know how to delete items from a Python dictionary and how to use variable-length arguments, try working on the practice question yourself.

Suggested Solution

The suggested solution for today’s question is as follows:

Click to see the suggested solution
def delKeys(dic, *keys):
    for i in keys:
        dic.pop(i, '')

The code above should be quite self-explanatory. We use a for loop to loop through *keys and use the pop() method to delete items from the dic dictionary.

That’s all for today. Hope you find it useful.

Written by Jamie | Last Updated September 25, 2020

Recent Posts