You can do this:
d.pop("", None)
d.pop(None, None)
Pops dictionary with a default value that you ignore.
Answer from Keith on Stack Overflowdictionary - Silently removing key from a python dict - Stack Overflow
Does the dictionary pop() method return an error if the key is not present?
python - dict.pop versus dict.get on the default return value - Stack Overflow
How can I remove a key from a Python dictionary? - Stack Overflow
If your primary concern is if a key exists within the dictionary, it should be done via 'my_key' in my_dict. .get and .pop as you can imagine serves slightly different purposes. .get is strictly retrieval, and .pop is retrieval and removal. You will want to use the respective method that best suit your use case, and employ a default value if you don't need to handle a KeyError.
As for the reason of why .pop doesn't use a default value by default, it is because that the operation expects to also remove a key from the dictionary. If the operation was completed successfully without raising an error, one might erroneously expect the key to be removed from the dictionary as well.
For .get, the method exists specifically as a alternative to provide a default value over the __getitem__ method, which you usually see the syntax as my_dict['my_key']. The latter of which, will raise a KeyError if the key doesn't exist.
get exists, in some sense, in two varieties: one raises a KeyError, the other doesn't.
>>> {}['my_key']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'my_key'
>>> {}.get('my_key')
>>>
pop, on the other hand, isn't an error-free version of another operation that raises a KeyError, so it's used in both situations: raising a KeyError by default, but returning a default value if requested.
>>> {}.pop('my_key')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'my_key'
>>> {}.pop('my_key', 3)
3
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.
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.