python 提示 keyError 的4种解决方法

python 提示 keyError 的4种解决方法本文介绍了五种处理 Python 字典中键不存在时避免 KeyError 的方法 包括 先检查键是否存在再操作 使用 get 方法 setdefault 方法 自定义 missing 方法和

大家好,欢迎来到IT知识分享网。

python 提示 keyError 的4种解决方法

在读取dictkeyvalue时,如果key不存在,就会触发KeyError错误,如:

Python


  1. t = {
  2. 'a': '1',
  3. 'b': '2',
  4. 'c': '3',
  5. }
  6. 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


  1. t = {
  2. 'a': '1',
  3. 'b': '2',
  4. 'c': '3',
  5. }
  6. if 'd' in t:
  7. print(t['d'])
  8. else:
  9. 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


  1. t = {
  2. 'a': '1',
  3. 'b': '2',
  4. 'c': '3',
  5. }
  6. 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


  1. t = {
  2. 'a': '1',
  3. 'b': '2',
  4. 'c': '3',
  5. }
  6. print(t.get('d', 'not exist'))
  7. 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,其valuedefault,并返回default;使用这个方法也永远不会触发KeyError,如:

Python


  1. t = {
  2. 'a': '1',
  3. 'b': '2',
  4. 'c': '3',
  5. }
  6. print(t.setdefault('d'))
  7. 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


  1. t = {
  2. 'a': '1',
  3. 'b': '2',
  4. 'c': '3',
  5. }
  6. print(t.setdefault('d', 'not exist'))
  7. 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


  1. t = {
  2. 'a': '1',
  3. 'b': '2',
  4. 'c': '3',
  5. }
  6. class Counter(dict):
  7. def __missing__(self, key):
  8. return None
  9. c = Counter(t)
  10. 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


  1. t = {
  2. 'a': '1',
  3. 'b': '2',
  4. 'c': '3',
  5. }
  6. class Counter(dict):
  7. def __missing__(self, key):
  8. return key
  9. c = Counter(t)
  10. print(c['d'])
  11. 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_factoryNone,则与dict无区别,会触发KeyError错误,如:

Python


  1. import collections
  2. t = {
  3. 'a': '1',
  4. 'b': '2',
  5. 'c': '3',
  6. }
  7. t = collections.defaultdict(None, t)
  8. 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


  1. import collections
  2. t = {
  3. 'a': '1',
  4. 'b': '2',
  5. 'c': '3',
  6. }
  7. def handle():
  8. return None
  9. t = collections.defaultdict(handle, t)
  10. 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


  1. import collections
  2. t = {
  3. 'a': '1',
  4. 'b': '2',
  5. 'c': '3',
  6. }
  7. t = collections.defaultdict(int, t)
  8. 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


  1. import collections
  2. t = {
  3. 'a': '1',
  4. 'b': '2',
  5. 'c': '3',
  6. }
  7. t = collections.defaultdict(list, t)
  8. 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>

Python


  1. import collections
  2. t = {
  3. 'a': '1',
  4. 'b': '2',
  5. 'c': '3',
  6. }
  7. t = collections.defaultdict(dict, t)
  8. 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>

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/120244.html

(0)
上一篇 2025-10-30 22:45
下一篇 2025-10-31 07:00

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信