Introduction

In this article, we’ll take a look at how to remove keys from Python dictionaries. This can be done with the pop() function, the del keyword, and with dict comprehensions.

Remove a Key Using _pop(key,d)

The pop(key, d) function removes a key from a dictionary and returns its value. It takes two arguments, the key is removed and the optional value to return if the key isn’t found. Here’s an example of popping an element with only the required key argument:

my_dict = {1: "a", 2: "b"}
popped_value = my_dict.pop(1)

line = "The value removed from the dictionary of the key: 1 is {}"
print(line.format(popped_value))

This snippet returns the following output:

The value removed from the dictionary of the key: 1 is a

Now, observe what happens when we try to remove a key that doesn’t exist:

my_dict = {1: "a", 2: "b"}
popped_value = my_dict.pop(3)

line = "The value removed from the dictionary of the key: 3 is {}"
print(line.format(popped_value))

This raises a KeyError, as expected since it doesn’t exist:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 3

If you call pop() on a key that doesn’t exist, Python would return a KeyError. So only use pop(key) if you’re confident that the key exists in the dictionary.

If you are unsure if the key exists then put a value for the second, optional argument for pop() - the default value. Instead of throwing a KeyError it will return that value.

#python #data structures

Python: How to Remove a Key from a Dictionary
2.55 GEEK