python dict.get()和dict['key']的區別

先看代碼:python

In [1]: a = {'name': 'wang'}

In [2]: a.get('age')

In [3]: a['age']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-a620cb7b172a> in <module>()
----> 1 a['age']

KeyError: 'age'

In [4]: a.get('age', 10)
Out[4]: 10

 

因此,dict['key']只能獲取存在的值,若是不存在則觸發KeyErrorblog

而dict.get(key, default=None)則若是不存在則返回一個默認值,若是設置了則是設置的,不然就是Noneip

In [6]: type(a.get('age'))
Out[6]: NoneType

  

 

相關文章
相關標籤/搜索