Categories
dictionary python unset

How can I remove a key from a Python dictionary?

2598

Is there a one-line way of deleting a key from a dictionary without raising a KeyError?

if 'key' in my_dict:
    del my_dict['key']

2

4159

To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():

my_dict.pop('key', None)

This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.

To delete a key that is guaranteed to exist, you can also use:

del my_dict['key']

This will raise a KeyError if the key is not in the dictionary.

12

  • 245

    Sometimes an advantage of using pop() over del: it returns the value for that key. This way you can get and delete an entry from a dict in one line of code.

    – kratenko

    Aug 18, 2013 at 12:21

  • 11

    In the question it is not required to keep the value. This would only add unneeded complexity. The answer from @zigg (below) is much better.

    Jun 14, 2017 at 2:05

  • 17

    @SalvatoreCosentino I can’t follow your argument. How is the code in this answer more complex than the code in in the other answer?

    Jun 15, 2017 at 13:52

  • 53

    @SalvatoreCosentino No, ignoring the return value of a function is not inefficient at all. Quite the opposite – this solution is much faster than the try/except solution if the key does not exist. You might find one or the other easier to read, which is fine. Both are idiomatic Python, so choose whatever you prefer. But claiming that this answer is more complex or inefficient simply makes no sense.

    Jun 15, 2017 at 18:44

  • 8

    @user5359531 I don’t understand. How is this a problem? None of the methods on Python’s built-in types returns self, so it would be rather surprising if this one did.

    Aug 2, 2018 at 10:09

431

Specifically to answer “is there a one line way of doing this?”

if 'key' in my_dict: del my_dict['key']

…well, you asked 😉

You should consider, though, that this way of deleting an object from a dict is not atomic—it is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of

try:
    del my_dict['key']
except KeyError:
    pass

which, of course, is definitely not a one-liner.

10

  • 34

    Yeah, pop is a definitely more concise, though there is one key advantage of doing it this way: it’s immediately clear what it’s doing.

    – zigg

    Jul 1, 2012 at 16:30

  • 6

    The try/except statement is more expensive. Raising an exception is slow.

    Aug 20, 2013 at 5:01

  • 20

    @ChrisBarker I’ve found if the key exists, try is marginally faster, though if it doesn’t, try is indeed a good deal slower. pop is fairly consistent but slower than all but try with a non-present key. See gist.github.com/zigg/6280653. Ultimately, it depends on how often you expect the key to actually be in the dictionary, and whether or not you need atomicity—and, of course, whether or not you’re engaging in premature optimization 😉

    – zigg

    Aug 20, 2013 at 12:18


  • 12

    I believe the value of clarity should not be overlooked. +1 for this.

    Jun 30, 2014 at 21:15

  • 3

    regarding expense of try/except, you can also go if 'key' in mydict: #then del.... I needed to pull out a key/val from a dict to parse correctly, pop was not a perfect solution.

    – Marc

    Jul 9, 2015 at 18:00

187

It took me some time to figure out what exactly my_dict.pop("key", None) is doing. So I’ll add this as an answer to save others googling time:

pop(key[, default])

If key is in the dictionary, remove it and return its value, else
return default. If default is not given and key is not in the
dictionary, a KeyError is raised.

Documentation

3

  • 24

    Just type help(dict.pop) in the python interpreter.

    Aug 6, 2013 at 18:07

  • 19

    help() and dir() can be your friends when you need to know what something does.

    Aug 6, 2013 at 18:08

  • 4

    or dict.pop? in IPython.

    Apr 13, 2014 at 1:09