您的位置:首页 > 编程语言 > Python开发

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

2017-07-12 17:36 465 查看
描述: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 dictiona4000ry.

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: