python dict.get()和dict['key']的区别

时间:2023-02-06 22:57:18

先看代码:

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']只能获取存在的值,如果不存在则触发KeyError

而dict.get(key, default=None)则如果不存在则返回一个默认值,如果设置了则是设置的,否则就是None

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

  

 python dict.get()和dict['key']的区别