Skip to content

Instantly share code, notes, and snippets.

@MattWoodhead
Created July 24, 2017 20:39
Show Gist options
  • Save MattWoodhead/6d39c0a7bc2ca375e809d6f04272b066 to your computer and use it in GitHub Desktop.
Save MattWoodhead/6d39c0a7bc2ca375e809d6f04272b066 to your computer and use it in GitHub Desktop.
Demonstration of Python's built in get() method for dictionaries
""" Easier to ask forgiveness than permission """
my_dict = {"key_0": 0,
"key_1": 10,
"key_2": 20,
"key_3": 30,
"key_4": 40,
}
# Verbose way
def my_dict_return(key_string):
try:
return my_dict[key_string]
except KeyError:
print("No matching key")
return None
my_dict_return("key_1")
>>> 10
my_dict_return("key_99")
>>> No matching key
# Pythonic way
my_dict.get("key_3", None)
>>> 30
my_dict.get("key_98", None)
>>>
# Awesome!! :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment