python 提示 keyError 的4种解决方法
https://blog.csdn.net/u011089523/article/details/72887163
在读取dict
的key
和value
时,如果key
不存在,就会触发KeyError
错误,如:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t['d'])
就会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">KeyError: 'd'
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span></span></code>
第一种解决方法
首先测试key是否存在,然后才进行下一步操作,如:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
if 'd' in t:
print(t['d'])
else:
print('not exist')
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">not exist
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span></span></code>
第二种解决方法
利用dict
内置的get(key[,default])
方法,如果key
存在,则返回其value
,否则返回default
;使用这个方法永远不会触发KeyError
,如:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t.get('d'))
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">None
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span></span></code>
加上default
参数:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t.get('d', 'not exist'))
print(t)
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">not exist
{'a': '1', 'c': '3', 'b': '2'}
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span><span style="display:block; counter-increment:linenumber 1"></span></span></code>
第三种解决方法
利用dict
内置的setdefault(key[,default])
方法,如果key
存在,则返回其value
;否则插入此key
,其value
为default
,并返回default
;使用这个方法也永远不会触发KeyError
,如:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t.setdefault('d'))
print(t)
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">None
{'b': '2', 'd': None, 'a': '1', 'c': '3'}
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span><span style="display:block; counter-increment:linenumber 1"></span></span></code>
加上default
参数:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t.setdefault('d', 'not exist'))
print(t)
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">not exist
{'c': '3', 'd': 'not exist', 'a': '1', 'b': '2'}
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span><span style="display:block; counter-increment:linenumber 1"></span></span></code>
第四种解决方法
向类dict
增加__missing__()
方法,当key
不存在时,会转向__missing__()
方法处理,而不触发KeyError
,如:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
class Counter(dict):
def __missing__(self, key):
return None
c = Counter(t)
print(c['d'])
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">None
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span></span></code>
更改return
值:
Python
t = {
'a': '1',
'b': '2',
'c': '3',
}
class Counter(dict):
def __missing__(self, key):
return key
c = Counter(t)
print(c['d'])
print(c)
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">d
{'c': '3', 'a': '1', 'b': '2'}
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span><span style="display:block; counter-increment:linenumber 1"></span></span></code>
第五种解决方法
利用collections.defaultdict([default_factory[,...]])
对象,实际上这个是继承自dict
,而且实际也是用到的__missing__()
方法,其default_factory
参数就是向__missing__()
方法传递的,不过使用起来更加顺手:
如果default_factory
为None
,则与dict
无区别,会触发KeyError
错误,如:
Python
import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
t = collections.defaultdict(None, t)
print(t['d'])
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">KeyError: 'd'
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span></span></code>
但如果真的想返回None
也不是没有办法:
Python
import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
def handle():
return None
t = collections.defaultdict(handle, t)
print(t['d'])
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">None
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span></span></code>
如果default_factory
参数是某种数据类型,则会返回其默认值,如:
Python
import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
t = collections.defaultdict(int, t)
print(t['d'])
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">0
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span></span></code>
又如:
Python
import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
t = collections.defaultdict(list, t)
print(t['d'])
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">[]
<span class="line-numbers-rows" style="position:absolute; top:0px; font-size:13.6px; left:-3.8em; width:3em; letter-spacing:-1px; border-right:1px solid rgb(153,153,153)"><span style="display:block; counter-increment:linenumber 1"></span></span></code>
注意:
如果dict
内又含有dict
,key
嵌套获取value
时,如果中间某个key
不存在,则上述方法均失效,一定会触发KeyError
:
Python
import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
t = collections.defaultdict(dict, t)
print(t['d']['y'])
会出现:
<code class="language-plain hljs" style="font-family:Consolas,Monaco,"Andale Mono","Ubuntu Mono",monospace; font-size:13.6px; padding:0px; background:transparent; margin:0px; word-spacing:normal; word-break:normal; word-wrap:normal; line-height:inherit; border:0px; display:inline; max-width:initial; overflow:initial; position:relative">KeyError: 'y'</code>
python 提示 keyError 的4种解决方法相关推荐
- python keyerror5种方法_Python操作dict时避免出现KeyError的几种解决方法
在读取dict的key和value时,如果key不存在,就会触发KeyError错误,如: t = { "a": "1", "b": &qu ...
- c语言蓝屏代码大全,window_Win10系统出现蓝屏提示错误代码0x00000050两种解决方法, 刚刚升级Win10系统的一段 - phpStudy...
Win10系统出现蓝屏提示错误代码0x00000050两种解决方法 刚刚升级Win10系统的一段时间,容易出现蓝屏的问题.导致蓝屏故障的原因各不相同,我们需要根据错误代码来执行正确的解决方法.比如,最 ...
- php7应用程序无法启动,window_win7系统打开软件提示应用程序无法启动的故障原因分析及2种解决方法, nbs - phpStudy...
win7系统打开软件提示应用程序无法启动的故障原因分析及2种解决方法 win7系统打开软件提示应用程序无法启动,因为应用程序的并行配置不正确,具体问题现象如下图所示: 故障原因分析: 一个可能是Win ...
- python无法使用1号gpu_详解tensorflow2.x版本无法调用gpu的一种解决方法
最近学校给了一个服务器账号用来训练神经网络使用,服务器本身配置是十路titan V,然后在上面装了tensorflow2.2,对应的python版本是3.6.2,装好之后用tf.test.is_gpu ...
- html文件打开系统错误,win7打开word提示“无法打开文件Normal因为内容有错误”的两种解决方法...
win7系统打开Word的时候,弹出提示"无法打开文件Normal.dotm,因为内容有错误",为什么会出现错误提示呢?小编就按照错误提示寻找文件,最后发现是Word自动生成的模板 ...
- 计算机无法连接无线信号,win7系统连接无线信号时提示Windows无法连接到路由器名称的四种解决方法...
现如今网络发展速度非常快,无线网络已经普及了,使用率高了遇到的问题也就多了.比如有时候笔记本win7系统连接无线信号时出现"Windows无法连接到路由器名称"(如下图所示),该如 ...
- w ndows10玩游戏蓝屏,Win10系统玩游戏蓝屏提示代码0x0000007E的两种解决方法
win10系统已经很多用户升级了,但是还是有不少用户在使用Ghost win10系统电脑的过程中经常遇到蓝屏问题,最近有位朋友在Win10系统玩游戏时出现蓝屏代码0x0000007E,显示一大串英文, ...
- python安装失败错误代码0x_详解雨林木风Win10提示“Python 0x80070643安装时发生严重错误”解决方法...
相信大家对于电脑非常不陌生吧,那你知道Win10专业版中提示"Python 0x80070643安装时发生严重错误"如何解决吗?是由于什么原因导致的呢?不知道了吧,其实系统错误非常 ...
- html没有注册类,电脑中ie浏览器提示没有注册类别的三种解决方法
ie浏览器功能十分强大,能够给我们带来很棒的网页浏览体验.不过,一些朋友反馈自己在使用ie浏览器过程中,突然遇到"没有注册类别"的出错提示,这是怎么回事呢?其实这是文件的丢失等原因 ...
最新文章
- Mind the Gap: Upgrading Genomes with Pacific Biosciences RS Long-Read Sequencing Technology
- Codeforces Round #275 (Div. 2) c
- SAP Spartacus 的 Above-the-Fold Loading 加载机制
- html 科幻模板,html5酷炫宇宙科幻周年庆典专题动画模板
- go 写入yaml_[Golang] 从零开始写Socket Server(4):将运行参数放入配置文件(XML/YAML)...
- 国内最受欢迎手游国际版折戟:腾讯也很无奈
- python编程(supervisor程序管理)
- #paragma详解
- PHP调用powershell权限,浏览器挂起执行运行Powershell的PHP
- Laravel文档阅读笔记-How to use @auth and @guest directives in Laravel
- 运动垫的全球与中国市场2022-2028年:技术、参与者、趋势、市场规模及占有率研究报告
- oracle导出BOM文件,ORACLE ERP导数据(BOM清单)
- 51单片机的键盘分类和运用
- 8个有用的表单构建工具,你一定要使用并收藏好
- 还在到处寻找画图软件?快来用Typora画饼图、时序图、流程图、UML图和状态图吧
- boost circular_buffer
- python 3.6 盲水印脚本安装说明
- 网络安全攻防在线学习平台总结
- 红外视频中的移动目标检测
- 「镁客·请讲」VR的拓荒者,幻境视界让VR内容拥有艺术之美
热门文章
- 基于seaborn的正太分布图
- linux C语言perror()函数(将错误消息写入标准错误)(把一个描述性错误消息输出到标准错误 stderr。首先输出自定义字符串 str,后跟一个冒号,然后是一个空格)
- golang 如何翻转含有中文 数字 英文字母等任意字符串
- 商场内导航地图有什么?商场导航地图哪个好用?
- 西门子wincc图形编辑器PDL文件密码保护
- php时间戳和js时间戳,js和PHP时间戳与日期转换
- 利用微信SDK实现只拍照
- 基于JavaEE的减脂训练营营员管理系统
- 共创共建共享,2023北京老博会陪伴企业成长宣传计划开启
- 判断点在直线的左侧和右侧的方法及原理