Created
July 24, 2017 20:39
-
-
Save MattWoodhead/6d39c0a7bc2ca375e809d6f04272b066 to your computer and use it in GitHub Desktop.
Demonstration of Python's built in get() method for dictionaries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" 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