您的位置:首页 > 编程语言 > Python开发

Python:操作dict时避免出现KeyError的几种方法

2017-06-06 20:29 162 查看
在读取
dict
key
value
时,如果
key
不存在,就会触发
KeyError
错误,如:

Python

t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t['d'])


就会出现:
KeyError: 'd'



第一种解决方法

首先测试key是否存在,然后才进行下一步操作,如:

Python

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
,如:

Python

t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t.get('d'))


会出现:
None


加上
default
参数:

Python

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
,如:

Python

t = {
'a': '1',
'b': '2',
'c': '3',
}
print(t.setdefault('d'))
print(t)


会出现:
None{'b': '2', 'd': None, 'a': '1', 'c': '3'}


加上
default
参数:

Python

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
,如:

Python

t = {
'a': '1',
'b': '2',
'c': '3',
}

class Counter(dict):

def __missing__(self, key):
return Nonec = Counter(t)
print(c['d'])


会出现:
None


更改
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)


会出现:
d
{'c': '3', 'a': '1', 'b': '2'}



第五种解决方法

利用
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'])


会出现:
KeyError: 'd'


但如果真的想返回
None
也不是没有办法:

Python

import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}

def handle():
return Nonet = collections.defaultdict(handle, t)
print(t['d'])


会出现:
None


如果
default_factory
参数是某种数据类型,则会返回其默认值,如:

Python

import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
t = collections.defaultdict(int, t)
print(t['d'])


会出现:
0


又如:

Python

import collections
t = {
'a': '1',
'b': '2',
'c': '3',
}
t = collections.defaultdict(list, t)
print(t['d'])


会出现:
[]


注意:
如果
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'])


会出现:
KeyError: 'y'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python dict keyerror
相关文章推荐