当前位置:主页 > 软件编程 > Python代码 >

解决Python获取字典dict中不存在的值时出错问题

时间:2021-07-08 14:49:19 | 栏目:Python代码 | 点击:

描述: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

您可能感兴趣的文章:

相关文章