通常我在在用字典时,都是按照字典的键值来获取字典里面的元素,举个栗子:
>>> a = {'a':1,'b':2}
>>> a['a']
1
>>> a['c']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'
可以看到,如果在取值的时候遇到所输入的键值不存在的情况,程序就会报错,出于某种目的,为了使程序能够继续运行下去,我们就可以使用 a.get(‘a’) 和 a.get(‘c’, ‘not exist’)
>>> a.get( 'c' , 'not exist') # 这里的'not exist'是自己设置的,当在a里找不到'c'时返回该字符串
'not exist'
>>> a.get('a')
1