1

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.

jpp
  • 159,742
  • 34
  • 281
  • 339
Helen Neely
  • 4,666
  • 8
  • 40
  • 64

2 Answers2

2

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')
jpp
  • 159,742
  • 34
  • 281
  • 339
1

Alternatively, you can use .get(key, [default_value]) to check if the item exists in OrderedDict. Details can be found in Python documentation on get method.

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'].get('Mandeep'):
    print('We have Mandeep')
else:
    print('No one by that name')

Output:

No one by that name

Explanation:

Here, we are searching for the name Mandeep in our OrderedDict people and if it is not found, it is set to None. Thus if the key is not found the else block is executed.

References:

arshovon
  • 13,270
  • 9
  • 51
  • 69