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
阅读全文
0 0
- Python获取字典dict中不存在的值时出错
- Python中dict 字典
- Python中dict字典使用方法
- Python中Dict字典用法
- Python中字典(dict)详解
- 用python字典(dict)获取更多的数据
- python 字典dict 的使用
- Python中实现两个字典(dict)合并的方法
- python中对字典(dict)的迭代
- python中字典(dict)的常用操作
- Python 中两个字典(dict)合并
- Python 中两个字典(dict)合并
- python中两个字典(dict)合并
- python读取xml放入dict字典中
- python中字典(dict)常见用法
- Python 中两个字典(dict)合并
- Python 中两个字典(dict)合并
- Python 中dict 字典方法小结
- CGAL Arrangements and Their Applications: A Step-By-Step Guide
- Kotlin Reference (十二) 内部类、枚举
- hadoop-2.6.0集群环境搭建
- 华为云计算 兼容性助手
- Openstack4J API初体验之启动一个实例并为实例分配IP(将实例挂在某个网段上)
- Python获取字典dict中不存在的值时出错
- FileReader与FileWriter
- 用js写的简洁笔记本(便于查看代码和运行结果 )
- vue-router进阶数据获取
- CSS样式
- Centos7 安装部署 Python-3.6.1
- source insight使用技巧
- 内存字节对齐
- Dubbo系列-1.概览