How to remove a key from a python dictionary?

Tony Source

When trying to delete a key from a dictionary, I write:

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

Is there a one line way of doing this?



answered 6 years ago Sven Marnach #1

Use 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 (ie. my_dict.pop('key')) and key does not exist, a KeyError is raised.

answered 6 years ago zigg #2

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

if 'key' in myDict: del myDict['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 myDict 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

    del myDict['key']
except KeyError:

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

answered 5 years ago Akavall #3

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


answered 3 years ago Marc Maxson #4

If you need to remove a lot of keys from a dictionary in one line of code, I think using map() is quite succinct and pythonic readable:

myDict = {'a':1,'b':2,'c':3,'d':4}
map(myDict.pop, ['a','c']) #the list of keys to remove
>>> myDict
{'b': 2, 'd': 4}

And if you need to catch errors where you pop a value that isn't in the dictionary, use lambda inside map() like this:

map(lambda x: myDict.pop(x,None), ['a','c','e'])
[1, 3, None] #pop returns
>>> myDict
{'b': 2, 'd': 4}

Works. and 'e' did not cause an error, even though myDict did not have an 'e' key.

answered 1 year ago Shameem #5

>>> if myDict.get(key): myDict.pop(key)

Another way

>>> {k:v for k, v in myDict.items() if k!='key'}

You can delete by conditions. No error if key doesn't exist

answered 1 year ago Peter Smit #6

Timing of the three solutions described above.

Small dictionary:

>>> import timeit
>>> timeit.timeit("d={'a':1}; d.pop('a')")
>>> timeit.timeit("d={'a':1}; del d['a']")
>>> timeit.timeit("d={'a':1}; d2 = {key: val for key, val in d.items() if key != 'a'}")

Larger dictionary:

>>> timeit.timeit("d={nr: nr for nr in range(100)}; d.pop(3)")
>>> timeit.timeit("d={nr: nr for nr in range(100)}; del d[3]")
>>> timeit.timeit("d={nr: nr for nr in range(100)}; d2 = {key: val for key, val in d.items() if key != 3}")

comments powered by Disqus