检查项目是否存在于OrderedDict字典中

时间:2018-12-05 11:13:10

标签: python python-3.x dictionary

出现关键错误,我看不出来要解决这个问题,所以我想知道是否有人可以让我知道我在做什么错。

代码如下:

>>> 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作为键。

任何帮助将不胜感激。

1 个答案:

答案 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')