7

In Python there are basically two ways to get a value from a dictionary:

  1. dictionary["key"]

  2. dictionary.get("key")

Is there any - maybe historical - reason for this behavior?

I sometimes stumble upon this while switching from JavaScript frontend development to Python backend development forgetting that dictionary["key"] results in a KeyError when the key is not present instead of returning None, which is the behaviour of the get method.

What is the background/design decision for those two ways? Is it for performance reasons - knowing a value is present reading it is more performant?

Thomas Junk
  • 9,623
  • 2
  • 26
  • 46

1 Answers1

15

Though I was not involved into the design of Python, I think I can make an educated guess:

 dictionary["key"]

is shorter and very convenient to use, since it is consistent with access to other containers like lists, tuples, or strings.

dictionary.get, however, has a different behaviour when the key is not contained in the dictionary, since it simply returns None and does not throw an exception. There are many use cases where this behaviour can be more handy and allows more concise code than adding a try/catch around a bracket statement. Note also there is a dictionary.get variant with 2 parameters which allows to specify an alternative to None.

So in short, both variants can be useful, and they are not interchangeable, since they have a different failure mode. Use square brackets when you prefer to get an exception in case of a missing key, and get when you prefer to get no exception (and a return value of None instead).

Doc Brown
  • 218,378