操作dict时避免出现KeyError的几种方法
在读取dict的key和value时,如果key不存在,就会触发KeyError错误,如:
t = {
'a': '',
'b': '',
'c': '',
}
print(t['d'])
就会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">KeyError: 'd'
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span></span></code>
第一种解决方法
首先测试key是否存在,然后才进行下一步操作,如:
t = {
'a': '',
'b': '',
'c': '',
}
if 'd' in t:
print(t['d'])
else:
print('not exist')
会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">not exist
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span></span></code>
第二种解决方法
利用dict内置的get(key[,default])方法,如果key存在,则返回其value,否则返回default;使用这个方法永远不会触发KeyError,如:
t = {
'a': '',
'b': '',
'c': '',
}
print(t.get('d'))
会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">None
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span></span></code>
加上default参数:
t = {
'a': '',
'b': '',
'c': '',
}
print(t.get('d', 'not exist'))
print(t)
会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">not exist
{'a': '1', 'c': '3', 'b': '2'}
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span><span style="display:block;"></span></span></code>
第三种解决方法
利用dict内置的setdefault(key[,default])方法,如果key存在,则返回其value;否则插入此key,其value为default,并返回default;使用这个方法也永远不会触发KeyError,如:
t = {
'a': '',
'b': '',
'c': '',
}
print(t.setdefault('d'))
print(t)
会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">None
{'b': '2', 'd': None, 'a': '1', 'c': '3'}
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span><span style="display:block;"></span></span></code>
加上default参数:
t = {
'a': '',
'b': '',
'c': '',
}
print(t.setdefault('d', 'not exist'))
print(t)
会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">not exist
{'c': '3', 'd': 'not exist', 'a': '1', 'b': '2'}
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span><span style="display:block;"></span></span></code>
第四种解决方法
向类dict增加__missing__()方法,当key不存在时,会转向__missing__()方法处理,而不触发KeyError,如:
t = {
'a': '',
'b': '',
'c': '',
}
class Counter(dict):
def __missing__(self, key):
return None
c = Counter(t)
print(c['d'])
会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">None
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span></span></code>
更改return值:
t = {
'a': '',
'b': '',
'c': '',
}
class Counter(dict):
def __missing__(self, key):
return key
c = Counter(t)
print(c['d'])
print(c)
会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">d
{'c': '3', 'a': '1', 'b': '2'}
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span><span style="display:block;"></span></span></code>
第五种解决方法
利用collections.defaultdict([default_factory[,...]])对象,实际上这个是继承自dict,而且实际也是用到的__missing__()方法,其default_factory参数就是向__missing__()方法传递的,不过使用起来更加顺手:
如果default_factory为None,则与dict无区别,会触发KeyError错误,如:
import collections
t = {
'a': '',
'b': '',
'c': '',
}
t = collections.defaultdict(None, t)
print(t['d'])
会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">KeyError: 'd'
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span></span></code>
但如果真的想返回None也不是没有办法:
import collections
t = {
'a': '',
'b': '',
'c': '',
} def handle():
return None
t = collections.defaultdict(handle, t)
print(t['d'])
会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">None
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span></span></code>
如果default_factory参数是某种数据类型,则会返回其默认值,如:
import collections
t = {
'a': '',
'b': '',
'c': '',
}
t = collections.defaultdict(int, t)
print(t['d'])
会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">0
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span></span></code>
又如:
import collections
t = {
'a': '',
'b': '',
'c': '',
}
t = collections.defaultdict(list, t)
print(t['d'])
会出现:
<code class="language-plain" style="font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:13.6px;background:transparent;word-spacing:normal;line-height:inherit;border:0px;display:inline;">[]
<span class="line-numbers-rows" style="font-size:13.6px;letter-spacing:-1px;border-right:1px solid rgb(153,153,153);"><span style="display:block;"></span></span></code>
注意:
如果dict内又含有dict,key嵌套获取value时,如果中间某个key不存在,则上述方法均失效,一定会触发KeyError:
import collections
t = {
'a': '',
'b': '',
'c': '',
}
t = collections.defaultdict(dict, t)
print(t['d']['y'])
实际操作:
for rb in data:
rb.setdefault('telephone') #当没有telephone时,设置为None
以上内容参考:https://blog.csdn.net/chenbindsg/article/details/73864045
操作dict时避免出现KeyError的几种方法的更多相关文章
- Python操作dict时避免出现KeyError的几种方法
见原文:https://www.polarxiong.com/archives/Python-%E6%93%8D%E4%BD%9Cdict%E6%97%B6%E9%81%BF%E5%85%8D%E5% ...
- Apache shiro集群实现 (八) web集群时session同步的3种方法
Apache shiro集群实现 (一) shiro入门介绍 Apache shiro集群实现 (二) shiro 的INI配置 Apache shiro集群实现 (三)shiro身份认证(Shiro ...
- 【转】web集群时session同步的3种方法
转载请注明作者:海底苍鹰地址:http://blog.51yip.com/server/922.html 在做了web集群后,你肯定会首先考虑session同步问题,因为通过负载均衡后,同一个IP访问 ...
- web集群时session同步的3种方法[转]
在做了web集群后,你肯定会首先考虑session同步问题,因为通过负载均衡后,同一个IP访问同一个页面会被分配到不同的服务器上,如果session不同步的话,一个登录用户,一会是登录状态,一会又不是 ...
- web集群时session同步的3种方法
在做了web集群后,你肯定会首先考虑session同步问题,因为通过负载均衡后,同一个IP访问同一个页面会被分配到不同的服务器上,如果session不同步的话,一个登录用户,一会是登录状态,一会又不是 ...
- C# 给PDF签名时添加时间戳的2种方法(附VB.NET代码)
在PDF添加签名时,支持添加可信时间戳来保证文档的法律效应.本文,将通过C#程序代码介绍如何添加可信时间戳,可通过2种方法来实现.文中附上VB.NET代码,有需可供参考. 一.程序运行环境 编译环境: ...
- 通过EF操作Sqlite时遇到的问题及解决方法
1.使用Guid作为字段类型时,能存,能查,但是作为查询条件时查询不到数据 解决方法:连接字符串加上;binaryguid=False
- asp.net操作GridView添删改查的两种方法 及 光棒效果
这部份小内容很想写下来了,因为是基础中的基础,但是近来用的比较少,又温习了一篇,发现有点陌生了,所以,还是写一下吧. 方法一:使用Gridview本身自带的事件处理,代码如下(注意:每次操作完都得重新 ...
- 一、winForm-DataGridView操作——控件绑定事件的两种方法
在winForm窗体中绑定(注册)事件的方法有两种: 一.绑定事件 双击控件,即进入.cs的代码编辑页面,会出现 类似于“ private void 控件名称_Click(object sender, ...
随机推荐
- 从0开始整合SSM框架--2.spring整合mybatis
依赖:<properties> <!-- spring版本号 --> <spring.version>4.1.3.RELEASE</spring.versio ...
- 数据结构(三)--- B树(B-Tree)
文章图片代码来自邓俊辉老师的课件 概述 上图就是 B-Tree 的结构,可以看到这棵树和二叉树有点不同---"又矮又肥".同时子节点可以有若干个小的子节点构成.那么这样一棵树 ...
- Vue2.0实现ie的兼容
转自:https://blog.csdn.net/landl_ww/article/details/79149461 1.解决方案:安装 "babel-polyfill" ,加配置 ...
- Vue 引入第三方js.css的方式
转自:https://blog.csdn.net/csdn_yudong/article/details/78795743 我们以 jQuery 为例,来讲解 一.绝对路径直接引入,全局可用 主入口页 ...
- vertical-align属性baseline(转)
图7-34 文字和图片内容默认垂直对齐方式为基线对齐 上一小节讲解了行高与单行纯文字的垂直居中,而如果行内含有图片和文字,在浏览器内浏览时,读者可以发现文字和图片在垂直方向并不是沿中线居中,而是沿基线 ...
- HTML中字体的垂直排列
1.源代码: <html> <head> </head> <body> <div style="font-size:18px;writi ...
- 撩课-Python-每天5道面试题-第1天
一. 尽可能详细的描述出一个应用软件, 比如QQ, 在计算机中运行时涉及的软硬件, 以及说明我们编程的侧重点? 电脑开机, 从硬盘中(外部存储设备)加载操作系统(系统软件)到内存(内部存储设备), 并 ...
- 常见IT英语单词
lable标签,master精通.主人,reference参考,release发布,schema模式,component组件,persistence持久化,generate生成产生,plugin插件, ...
- Linux 目录结构说明
根目录是整个系统最重要的一个目录,因为不但所有的目录都是由根目录衍生出来的,同时根目录也与开机/还原/系统修 复等动作有关. 由于系统开机时需要特定的开机软件.核心文件.开机所需程序.函数库等等文件数 ...
- JDBC入门(1)—— 入门案例
JDBC(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组 ...