I noticed that for the standard dict
in Python, there are two ways to get an element from the dictionary:
# First we create a `dict`:
my_dict = {'greeting': 'hello'}
# And now we can read from it, as such:
my_greeting = my_dict['greeting'] # `my_greeting` is now 'hello'.
# But this also works:
my_greeting = my_dict.get('greeting') # `my_greeting` is now also 'hello'.
The only difference that I can find is that for a key that doesn't exist, indexing throws a KeyError
, while get
silently fails and returns None
.
It seems to me that this makes no difference in practice, because with indexing one needs to use try/except
and with get
one needs to use if/else
to check for a missing value. (In my experience a variable ending up being None
means that at some point you need to handle this much like you'd handle an error, it's hardly ever intentional).
If anything, indexing seems more Pythonic: "Errors should never pass silently, unless explicitly silenced". Unless you count using get
as "explicitly silencing" which seems absurd, an error passing silently seems to be exactly what it does.
But that then begs the question: Why is there such a thing as get
for a dict
, and when is it ever appropriate to use it?