.get python
# The get() method on dicts
# and its "default" argument
name_for_userid = {
382: "Alice",
590: "Bob",
951: "Dilbert",
}
def greeting(userid):
return "Hi %s!" % name_for_userid.get(userid, "there")
>>> greeting(382)
"Hi Alice!"
>>> greeting(333333)
"Hi there!"
'''When "get()" is called it checks if the given key exists in the dict.
If it does exist, the value for that key is returned.
If it does not exist then the value of the default argument is returned instead.
'''
# transferred by @ebdeuslave
# From Dan Bader - realpython.com
dic = {"A": 1, "B": 2}
print(dic["A"])
print(dic["C"])
# This would produce a KeyError saying the key was not found
# To avoid these situations, we use the get() function
# If it finds nothing, it'll return None instead of an error.
print(dic.get("C")) # None
print(dic.get("C","Not Found ! ")) # Not Found !
# You can specify what the other value can be, like the example above.