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
相关文章推荐
- 解决Python获取字典dict中不存在的值时出错问题
- [python]用eval强制将字符串转换为字典变量时候出错:NameError: name 'null' is not defined[python]用eval函数 字符串转dict
- 用python字典(dict)获取更多的数据
- Python 中两个字典(dict)合并
- 列表(list)和字典(dict)数据排序 Python
- python 将字符串转换成字典dict
- Python中将字符串类型转为字典类型(string to dict)
- python学习五 列表(list)、字典(dict)、字符串(string)
- python 字典(dict)get方法应用
- python小例子之4 -- 列表(list)和字典(dict)数据排序
- Python dict dictionaries Python 数据结构——字典
- 【Python基础】之对字典进行排序操作(sort by the values of dict)
- Python源码剖析[12] —— 字典对象PyDictObject(1)
- Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
- python dict字典
- python 将字符串转换成字典dict
- Python源码剖析[13] —— 字典对象PyDictObject(2)
- 【Python】-字典DICT常用函数实例
- python 从字典里取出内容,创建集合 dict -> set
- Python的字典get方法:从字典中获取一个值