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
Why dict.get(key) instead of dict[key]?
Comparing to dict[key]
, dict.get
provides a fallback value when looking up for a key.
get(key[, default]) 4. Built-in Types — Python 3.6.4rc1 documentation
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
d = {"Name": "Harry", "Age": 17}
In [4]: d['gender']
KeyError: 'gender'
In [5]: d.get('gender', 'Not specified, please add it')
Out[5]: 'Not specified, please add it'
If without default value
, you have to write cumbersome codes to handle such an exception.
def get_harry_info(key):
try:
return "{}".format(d[key])
except KeyError:
return 'Not specified, please add it'
In [9]: get_harry_info('Name')
Out[9]: 'Harry'
In [10]: get_harry_info('Gender')
Out[10]: 'Not specified, please add it'
As a convenient solution, dict.get
introduces an optional default value avoiding above unwiedly codes.
dict.get
has an additional default value option to deal with exception if key is absent from the dictionary