Why dict.get(key) instead of dict[key]?

后端 未结 10 2488
生来不讨喜
生来不讨喜 2020-11-21 05:51

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

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 06:18

    Why dict.get(key) instead of dict[key]?

    0. Summary

    Comparing to dict[key], dict.get provides a fallback value when looking up for a key.

    1. Definition

    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'
    

    2. Problem it solves.

    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.

    3. Conclusion

    dict.get has an additional default value option to deal with exception if key is absent from the dictionary

提交回复
热议问题