出现关键错误,我看不出来要解决这个问题,所以我想知道是否有人可以让我知道我在做什么错。
代码如下:
>>> from collections import OrderedDict
>>> people = OrderedDict()
>>> people['Depark'] = 'Jaipor'
>>> people['James'] = 'Walubi'
>>>
>>> work = OrderedDict()
>>> work['Train drive'] = 'Big_train'
>>> work['Teacher'] = 'Maths_teacher'
>>>
>>>
>>> def props():
... d = dict()
... d['people'] = people
... d['work'] = work
... return d
>>> test = props()
>>> if test['people']['Mandeep']:
... print 'We have Mandeep'
... else:
... print 'No one by that name'
这是错误消息:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Mandeep'
我期望它能打印'No one by that name'
,因为我们没有Mandeep作为键。
任何帮助将不胜感激。
答案 0 :(得分:1)
test['people']['Mandeep']
条件之前,先评估 if
。毫不奇怪,它会引发KeyError
。一种Python解决方案是使用try
/ except
构造:
try:
test['people']['Mandeep']
print('We have Mandeep')
except KeyError:
print('No one by that name')
如果想要使用if
/ else
子句,则可以检查该子词典中是否存在该键:
if 'Mandeep' in test['people']:
print('We have Mandeep')
else:
print('No one by that name')