We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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
ifkey
is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises aKeyError
.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.