How to remove a key from a Python dictionary?

2019-01-01 01:27发布

问题:

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?

回答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.



回答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

try:
    del myDict[\'key\']
except KeyError:
    pass

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



回答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

Documentation



回答4:

Timing of the three solutions described above.

Small dictionary:

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

Larger dictionary:

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


回答5:

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}

It works. And \'e\' did not cause an error, even though myDict did not have an \'e\' key.



回答6:

Use:

>>> 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.



回答7:

Using the \"del\" keyword:

del dict[key]


回答8:

We can delete a key from a Python dictionary by the some following approaches.

Using the del keyword; it\'s almost the same approach like you did though -

 myDict = {\'one\': 100, \'two\': 200, \'three\': 300 }
 print(myDict)  # {\'one\': 100, \'two\': 200, \'three\': 300}
 if myDict.get(\'one\') : del myDict[\'one\']
 print(myDict)  # {\'two\': 200, \'three\': 300}

Or

We can do like following:

But one should keep in mind that, in this process actually it won\'t delete any key from the dictionary rather than making specific key excluded from that dictionary. In addition, I observed that it returned a dictionary which was not ordered the same as myDict.

myDict = {\'one\': 100, \'two\': 200, \'three\': 300, \'four\': 400, \'five\': 500}
{key:value for key, value in myDict.items() if key != \'one\'}

If we run it in the shell, it\'ll execute something like {\'five\': 500, \'four\': 400, \'three\': 300, \'two\': 200} - notice that it\'s not the same ordered as myDict. Again if we try to print myDict, then we can see all keys including which we excluded from the dictionary by this approach. However, we can make a new dictionary by assigning the following statement into a variable:

var = {key:value for key, value in myDict.items() if key != \'one\'}

Now if we try to print it, then it\'ll follow the parent order:

print(var) # {\'two\': 200, \'three\': 300, \'four\': 400, \'five\': 500}

Or

Using the pop() method.

myDict = {\'one\': 100, \'two\': 200, \'three\': 300}
print(myDict)

if myDict.get(\'one\') : myDict.pop(\'one\')
print(myDict)  # {\'two\': 200, \'three\': 300}

The difference between del and pop is that, using pop() method, we can actually store the key\'s value if needed, like the following:

myDict = {\'one\': 100, \'two\': 200, \'three\': 300}
if myDict.get(\'one\') : var = myDict.pop(\'one\')
print(myDict) # {\'two\': 200, \'three\': 300}
print(var)    # 100

Fork this gist for future reference, if you find this useful.