如果字典中key不存在,程序会报错'KeyError',如下:
def test_no_key(self): a_dict = {} print(a_dict['a_key'])
Error Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 59, in testPartExecutor yield File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 605, in run testMethod() File "/Users/wmj/PycharmProjects/fluent/test/test_dict.py", line 30, in test_no_key print(a_dict['a_key']) KeyError: 'a_key'
采用dict.get()的方式,如果key不存在,怎会返回None
a_dict = {} result = a_dict.get('a_key') print(type(result))
并且可以自定义默认值,比如如果返回‘nothing'
a_dict = {} print(a_dict.get('a_key', 'nothing'))