If you have a sensible default for dict lookups you can use a dict's .get()
method.
But be cautious: not setting a default value, dict.get()
returns None
if the key is not in the dictionary requiring additional checks.
So it's usually better to return a default value of the same type for consistency. 💡
Below some practical examples. 🛠️
# look for preferences file, else load in a default (local) one
preference_file = os.environ.get("EMOJI_PREFERENCES", ".preferences")
# get letter score or if not in mapping default to 0
def calc_word_value(word):
"""Calc a given word value based on Scrabble LETTER_SCORES mapping"""
return sum(LETTER_SCORES.get(char.upper(), 0) for char in word)
# some options are "required", others have a default set
def lambda_handler(event, context):
bite_id = event["bite_id"]
environment = event["environment"]
is_codeonly = event.get("is_codeonly", False)
is_test_bite = event.get("is_test_bite", False)
#dicts