Check that item exists in a dictionary of OrderedDict


I can't see to get this working, having key error so was wondering if anyone could let me know what I'm doing wrong.

Here is the code:

>>> 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'

This is the error message:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Mandeep'

I was expecting it to print 'No one by that name' as we don't have Mandeep as a key.

Any help would be appreciated.


Answer

test['people']['Mandeep'] is evaluated before the if condition is processed. Unsurprisingly, it raises KeyError. One Pythonic solution is to use a try / except construct:

try:
    test['people']['Mandeep']
    print('We have Mandeep')
except KeyError:
    print('No one by that name')

If you want to use an if / else clause, you can check if the key exists in your sub-dictionary:

if 'Mandeep' in test['people']:
    print('We have Mandeep')
else:
    print('No one by that name')