在讀取dict的key和value時,如果key不存在,就會觸發KeyError錯誤,如:
1
2
3
4
5
6
|
t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } print (t[ 'd' ]) |
就會出現:
KeyError: 'd'
第一種解決方法
首先測試key是否存在,然后才進行下一步操作,如:
1
2
3
4
5
6
7
8
9
|
t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } if 'd' in t: print (t[ 'd' ]) else : print ( 'not exist' ) |
會出現:
not exist
第二種解決方法
利用dict內置的get(key[,default])方法,如果key存在,則返回其value,否則返回default;使用這個方法永遠不會觸發KeyError,如:
1
2
3
4
5
6
|
t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } print (t.get( 'd' )) |
會出現:
None
加上default參數:
1
2
3
4
5
6
7
|
t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } print (t.get( 'd' , 'not exist' )) print (t) |
會出現:
not exist
{'a': '1', 'c': '3', 'b': '2'}
第三種解決方法
利用dict內置的setdefault(key[,default])方法,如果key存在,則返回其value;否則插入此key,其value為default,并返回default;使用這個方法也永遠不會觸發KeyError,如:
1
2
3
4
5
6
7
|
t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } print (t.setdefault( 'd' )) print (t) |
會出現:
None
{'b': '2', 'd': None, 'a': '1', 'c': '3'}
加上default參數:
1
2
3
4
5
6
7
|
t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } print (t.setdefault( 'd' , 'not exist' )) print (t) |
會出現:
not exist
{'c': '3', 'd': 'not exist', 'a': '1', 'b': '2'}
第四種解決方法
向類dict增加__missing__()方法,當key不存在時,會轉向__missing__()方法處理,而不觸發KeyError,如:
1
2
3
4
5
6
7
8
9
10
11
12
|
t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } class Counter( dict ): def __missing__( self , key): return None c = Counter(t) print (c[ 'd' ]) |
會出現:
None
更改return值:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } class Counter( dict ): def __missing__( self , key): return key c = Counter(t) print (c[ 'd' ]) print (c) |
會出現:
d
{'c': '3', 'a': '1', 'b': '2'}
第五種解決方法
利用collections.defaultdict([default_factory[,...]])對象,實際上這個是繼承自dict,而且實際也是用到的__missing__()方法,其default_factory參數就是向__missing__()方法傳遞的,不過使用起來更加順手:
如果default_factory為None,則與dict無區別,會觸發KeyError錯誤,如:
1
2
3
4
5
6
7
8
|
import collections t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } t = collections.defaultdict( None , t) print (t[ 'd' ]) |
會出現:
KeyError: 'd'
但如果真的想返回None也不是沒有辦法:
1
2
3
4
5
6
7
8
9
10
11
|
import collections t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } def handle(): return None t = collections.defaultdict(handle, t) print (t[ 'd' ]) |
會出現:
None
如果default_factory參數是某種數據類型,則會返回其默認值,如:
1
2
3
4
5
6
7
8
|
import collections t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } t = collections.defaultdict( int , t) print (t[ 'd' ]) |
會出現:
0
又如:
1
2
3
4
5
6
7
8
|
import collections t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } t = collections.defaultdict( list , t) print (t[ 'd' ]) |
會出現:
[]
注意:
如果dict內又含有dict,key嵌套獲取value時,如果中間某個key不存在,則上述方法均失效,一定會觸發KeyError:
1
2
3
4
5
6
7
8
|
import collections t = { 'a' : '1' , 'b' : '2' , 'c' : '3' , } t = collections.defaultdict( dict , t) print (t[ 'd' ][ 'y' ]) |
會出現:
KeyError: 'y'
到此這篇關于Python操作dict時避免出現KeyError的幾種解決方法的文章就介紹到這了,更多相關Python操作dict出現KeyError內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/u011089523/article/details/72887163