描述: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
本文介绍在Python2.7中如何安全地从字典中获取一个可能存在或不存在的值,避免程序因键不存在而抛出异常。推荐使用dict.get()方法,并详细解释了该方法的参数及返回值。

16万+

被折叠的 条评论
为什么被折叠?



