Python: How to Remove a Key from a Dictionary

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.

The above snippet can be rewritten as:

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

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

And now it doesn't throw an error when we run it:

The value removed from the dictionary of the key: 3 is None

Remove a Key Using del dict[key]

Another way to remove a key from a dictionary is through the del keyword. This keyword can remove any object. It can also delete a key-value pair of a dictionary like this: del dict_name[key]:

my_dict = {1: "a", 2: "b"}
del my_dict[1]

line = "The dictionary after deletion is {}"
print(line.format(my_dict))

The above snippet returns the following output, denoting the dictionary with just the left out value(s):

The dictionary after deletion is {2: 'b'}

Unlike pop(), no value is returned when deleted. If you are looking to preserve the existing dictionary input, you can find the next section to be useful.

Remove Multiple Dictionary Keys with Dict Comprehensions

The previous methods update a dictionary in-place, meaning that the key-value pair is destroyed. If the original key needs to be preserved, we can use a custom function to do so. In Python, it's commonly known that we can use list comprehensions to create a new list based on an existing one. We can do the same with dictionaries using dict comprehensions.

So instead of deleting values in a list, we can use a dict comprehension to create a new dictionary with a condition that excludes the values we don't want.

Take the following example where we create a new dictionary that doesn't have a key of 1:

my_dict = {1: "a", 2: "b"}
my_dict2 = {k: v for k, v in my_dict.items() if k != 1}

line = "The new dictionary is {}"
print(line.format(my_dict2))
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This snippet generates the following output, printing the new dictionary:

The new dictionary is {2: 'b'}

Note that we're creating a new dictionary, adding to our program's memory usage. For dictionaries of bigger sizes, if we don't exclude a lot of members then we're nearly doubling the memory used for that data.

Benchmarking Function Efficiency

We have observed three methods so far. But which method is the fastest among the three?

Let's create a random dictionary on which we will be testing out our methods. The following function gen_random_dict(n) takes a list as an argument and creates a dictionary with random seeded integers:

import random

def gen_random_dict(n):
    random.seed(0)
    mydict = {}
    for i in range(n):
        nmbr = random.randrange(1, n, 1)
        mydict[nmbr] = "value "+ str(nmbr)
    return mydict

In this same file, let's add some functions that delete a key in each of the ways we discussed:

# Remove a key using pop function
def remove_using_pop(dict_input):
    dict_input.pop(1)
    return None


# Remove a key using del keyword
def remove_using_del(dict_input):
    del dict_input[1]
    return None


# Remove a key using condition
def remove_using_condition(dict_input):
    return {k: v for k, v in dict_input.items() if k != 1}

Finally, add the following code that uses the timeit module that measures the execution time of our code:

import timeit


if __name__ == "__main__":
    func_to_be_tested = "remove_using_pop(gen_random_dict(10000))"
    setup_stmt = "from __main__ import remove_using_pop, gen_random_dict"
    runtime1 = timeit.timeit(func_to_be_tested, setup=setup_stmt, number=1)
    func_to_be_tested = "remove_using_del(gen_random_dict(10000))"
    setup_stmt = "from __main__ import remove_using_del, gen_random_dict"
    runtime2 = timeit.timeit(func_to_be_tested, setup=setup_stmt, number=1)
    func_to_be_tested = "remove_using_condition(gen_random_dict(10000))"
    setup_stmt = "from __main__ import remove_using_condition, gen_random_dict"
    runtime3 = timeit.timeit(func_to_be_tested, setup=setup_stmt, number=1)
    print("Runtime for removing key from Dict:")
    print("\t1) Using Pop: {}".format(str(runtime1)))
    print("\t2) Using Del: {}".format(str(runtime2)))
    print("\t3) Using Condition: {}".format(str(runtime3)))

While results may vary on your computer, the pattern should be consistent. Here's the output we got after executing this script:

Runtime for removing key from Dict:
        1) Using Pop: 0.015606499999194057
        2) Using Del: 0.01090950000070734
        3) Using Condition: 0.011443700001109391

Using the del keyword has an edge over the rest of the methods. Although the time difference doesn't seem to be very dramatic on smaller dictionaries. Though, it will make a huge impact when the size of the dictionary is large.

Conclusion

In this article, we learned three ways by which a key-value pair can be removed from a dictionary - pop(), del, and dict comprehensions. Choosing the right method for the right size of dictionary can help in decreasing the runtime of the script and the memory usage.

Last Updated: September 19th, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Sathiya Sarathi GunasekaranAuthor

Pythonist 🐍| Linux Geek who codes on WSL | Data & Cloud Fanatic | Blogging Advocate | Author

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms