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

后端 未结 10 2486
生来不讨喜
生来不讨喜 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:12

    get takes a second optional value. If the specified key does not exist in your dictionary, then this value will be returned.

    dictionary = {"Name": "Harry", "Age": 17}
    dictionary.get('Year', 'No available data')
    >> 'No available data'
    

    If you do not give the second parameter, None will be returned.

    If you use indexing as in dictionary['Year'], nonexistent keys will raise KeyError.

提交回复
热议问题