0

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?

Lara
  • 2,594
  • 4
  • 24
  • 36

1 Answers1

3

Why is there such a thing as get for a dict, and when is it ever appropriate to use it?

You might provide get with second value, which will be provided if key was not found for example

dct = {"A":1}
value = dct.get("B",0)
print(value)

output:

0

This is useful, when using default value for non-present keys makes sense.

Daweo
  • 31,313
  • 3
  • 12
  • 25