Today, I came across the dict
method get
which, given a key in the dictionary, returns the associated value.
For what purpose is this funct
It allows you to provide a default value if the key is missing:
dictionary.get("bogus", default_value)
returns default_value
(whatever you choose it to be), whereas
dictionary["bogus"]
would raise a KeyError
.
If omitted, default_value
is None
, such that
dictionary.get("bogus") # <-- No default specified -- defaults to None
returns None
just like
dictionary.get("bogus", None)
would.
One difference, that can be an advantage, is that if we are looking for a key that doesn't exist we will get None, not like when we use the brackets notation, in which case we will get an error thrown:
print(dictionary.get("address")) # None
print(dictionary["address"]) # throws KeyError: 'address'
Last thing that is cool about the get method, is that it receives an additional optional argument for a default value, that is if we tried to get the score value of a student, but the student doesn't have a score key we can get a 0 instead.
So instead of doing this (or something similar):
score = None
try:
score = dictionary["score"]
except KeyError:
score = 0
We can do this:
score = dictionary.get("score", 0)
# score = 0
Based on usage should use this get
method.
Example1
In [14]: user_dict = {'type': False}
In [15]: user_dict.get('type', '')
Out[15]: False
In [16]: user_dict.get('type') or ''
Out[16]: ''
Example2
In [17]: user_dict = {'type': "lead"}
In [18]: user_dict.get('type') or ''
Out[18]: 'lead'
In [19]: user_dict.get('type', '')
Out[19]: 'lead'
The purpose is that you can give a default value if the key is not found, which is very useful
dictionary.get("Name",'harry')