How to remove a key from a Python dictionary?

2019-01-01 01:41发布

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?

8条回答
梦寄多情
2楼-- · 2019-01-01 01:42

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.

查看更多
妖精总统
3楼-- · 2019-01-01 01:43

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
查看更多
何处买醉
4楼-- · 2019-01-01 01:47

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.

查看更多
人间绝色
5楼-- · 2019-01-01 01:57

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.

查看更多
深知你不懂我心
6楼-- · 2019-01-01 01:57

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楼-- · 2019-01-01 02:01

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.

查看更多
登录 后发表回答