Explaining differences between dict.get(key) and dict[key] in Python

twisted imaginary coupled with knowledge helps to memorize it longer | keys to heaven, vatican, realist

The aim of this explainer💡 is to define the difference between

in Python.

1. Get() is used when the missing key should not throw an exception, [] syntax when it should

  • It allows you to provide a default value/expression if the key is missing
  • …a sort of if/then mechanism without an if statement
  • If omitted in the .get() , default_value is None, such that
  • is the same as
  • however, checking for a non-existent key with [] syntax throws an ERROR
  • raises a KeyError which you can properly catch if needed

2. Let’s get to real life: I am get() this for say checking a value of an environmental variable

  • I’m in a Docker
  • I am doing case analysis based on environmental variables and I don’t want the script to crash if a key is not found
  • A simple reason is that I can look_up org_id in one container based on a nicer client tags

3. In addition, you can return values for non-found keys by using get()

  • the following counts words in a string
  • frequencies.get(word, 0) means that
  • KeyError is never raised because of the use of get method
  • the 0 is another optional parameter to be returned as a value if the key does not exist
  • the default is None

LINKS

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com