#pattern #python

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:

1my_dict = {"key": "value"}
2
3val = ""
4if "key" in my_dict:
5    val = my_dict["key"]

You can make it shorter by writing:

1my_dict = {"key": "value"}
2
3val = my_dict["key"] if "key" in my_dict else ""

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

1my_dict = {"key": "value"}
2
3val = 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:

1my_dict = {"key": "value", "empty": ""}
2
3val = 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:

1import os
2
3db_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.