操作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, ...
随机推荐
- AngularJs ng-repeat重复项异常解决方案
ng-repeat="v in arr track by $index" <!DOCTYPE html> <html lang="en"> ...
- shell通过ping检测整个网段IP的网络状态脚本
要实现Ping一个网段的所有IP,并检测网络连接状态是否正常,很多方法都可以实现,下面简单介绍两种,如下:脚本1#!/bin/sh# Ping网段所有IP# 2012/02/05ip=1 #通过修改初 ...
- C# Winform 跨线程更新UI控件常用方法汇总
https://www.cnblogs.com/marshal-m/p/3201051.html
- C# 字符串处理—— 去除首位保留其他
//去除首位 public static string RemoveFirstPlace(string s) { ) //输入空值直接Return { ")) //判断开头是否是零 s = ...
- 怎么使用fiddler 测试post get 接口
直接上图 测试 post
- Hadoop源码学习笔记(6)——从ls命令一路解剖
Hadoop源码学习笔记(6) ——从ls命令一路解剖 Hadoop几个模块的程序我们大致有了点了解,现在我们得细看一下这个程序是如何处理命令的. 我们就从原头开始,然后一步步追查. 我们先选中ls命 ...
- 02:奇数单增序列 个人博客doubleq.win
个人博客doubleq.win 02:奇数单增序列 查看 提交 统计 提问 总时间限制: 1000ms 内存限制: 65536kB 描述 给定一个长度为N(不大于500)的正整数序列,请将其中的所 ...
- OSMC Vs. OpenELEC Vs. LibreELEC – Kodi Operating System Comparison
Kodi's two slim-and-trim kid brothers LibreELEC and OpenELEC were once great solutions for getting t ...
- EF6 按条件更新多行记录的值
using (var db = new MyDbContext()) { string fromUser = ""; //sender string toUser = " ...
- Servlet:从入门到实战学习(3)---Servlet实例【图文】
本篇通过图文实例给大家详细讲述如何建立一个Servlet,配置好运行环境并成功连接到MYSQL的数据库,进行数据的查询展示. 1.项目创建:IDEA -> Create New Project ...