I'm trying to figure out what is the reason for having None
as the default value for dict.get
but no default value (without specifying the default value) for dict.pop
{}.get('my_key')
# output: None
{}.pop('my_key')
# output: KeyError: 'my_key'
I was thinking that the reason for not having implicit default value for dict.pop
is because you may have keys with value None
so, in order to not get confused if your key is in the dictionary or not, an implicit default value for dict.pop
doesn't make so much sense. But then again this explanation should be valid also for dict.get
and isn't:
{'my_key': None}.get('my_key')
# output: None
# but doesn't tell you if the key is truly in the dictionary or not
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With