Python获取字典dict中不存在的值时出错

来源:互联网 发布:修复linux grub引导 编辑:程序博客网 时间:2024/06/18 11:17

描述:Python2.7中如果想要获取字典中的一个值,但是这个值可能不存在,此时应该加上判断:

举个例子:

t= {}if t.get('1'): # right:这种通过key来查询是否存在的方式是比较好的   print(t['1'])print('right')if t['1']: # wrong:这种直接判断是否存在的方式因为会在判断之前调用,所以会报错
   print(t['1'])
额外说明:
dict.get(key, default=None)方法详解:

Parameters:

key -- This is the Key to be searched in the dictionary.

default -- This is the Value to be returned in case key does not exist. 如果default没指定,而且没有搜到值的话,会返回None



原创粉丝点击