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?
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?
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:
And if you need to catch errors where you pop a value that isn't in the dictionary, use lambda inside map() like this:
It works. And 'e' did not cause an error, even though myDict did not have an 'e' key.
Timing of the three solutions described above.
Small dictionary:
Larger dictionary:
Specifically to answer "is there a one line way of doing this?"
...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 inmyDict
during theif
statement, but may be deleted beforedel
is executed, in which casedel
will fail with aKeyError
. Given this, it would be safest to either usedict.pop
or something along the lines ofwhich, of course, is definitely not a one-liner.
Use
dict.pop()
:This will return
my_dict[key]
ifkey
exists in the dictionary, andNone
otherwise. If the second parameter is not specified (ie.my_dict.pop('key')
) andkey
does not exist, aKeyError
is raised.Use:
Another way:
You can delete by conditions. No error if
key
doesn't exist.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 -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
.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 asmyDict
. Again if we try to printmyDict
, 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:Now if we try to print it, then it'll follow the parent order:
Or
Using the
pop()
method.The difference between
del
andpop
is that, usingpop()
method, we can actually store the key's value if needed, like the following:Fork this gist for future reference, if you find this useful.