One of those small nice things in Python I always tend to forget is how to get a value from a dictionary in a safe manner.

You can do:

my_dict = {"key": "value"}

val = ""
if "key" in my_dict:
    val = my_dict["key"]

You can make it shorter by writing:

my_dict = {"key": "value"}

val = my_dict["key"] if "key" in my_dict else ""

However, by far, the easiest one to read is:

my_dict = {"key": "value"}

val = my_dict.get("key", "")

One caveat though, the get function only checks if the key exists, not if it contains an actual value or not.

If you want to cover that scenario as well, you need to do:

my_dict = {"key": "value", "empty": ""}

val = my_dict.get("empty") or "default"

I use this a lot when you want to get the value of an environment varaible and provide a default value if needed:

import os

db_type = os.environ.get("db_type") or "sqlite"

In the Python docs, it's explained as:

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

Related Posts

  • Making a unique list in Python preserving the order
  • Sorting a Python dict by value
  • Annotate Querysets to Fetch Specific Values
  • Optimize Database Calls with Prefetch Related and Select Related
  • Testing exceptions in pytest