0

I need to check in the professor key whether 'samplesubject' is present or not.

I am getting key error since samplesubject is not in the main dictionary, searchtest.

Sample Dictionary is below

searchtest = \
[{'_id': '6',
  '_index': 'courses',
  '_score': 1.0,
  '_source': {'name': 'Cost Accounting 400',
              'professor': {'department': 'accounting',
                            'email': 'cageb@onuni.com',
                            'facutly_type': 'full-time',
                            'name': 'Bill Cage'},
              'room': 'E7',
              'students_enrolled': 31}},
 {'_id': '1',
  '_index': 'courses',
  '_score': 1.0,
  '_source': {'name': 'Accounting 101',
              'professor': {'department': 'finance',
                            'email': 'baszot@onuni.com',
                            'facutly_type': 'part-time',
                            'name': 'Thomas Baszo'},
              'room': 'E3',
              'students_enrolled': 27}}]    
   

Code is below

    prof_list = []
    prof_dict = {'name': None, 'samplesubject': None}
    for each in searchtest[0]:
        print (each['_source'])
        if 'professor' in each:
            prof_dict['name'] = each['_source']['professor'][0]['name']
            prof_dict['samplesubject'] = each['_source']['professor'][0]['samplesubject']
            prof_dict.append(prof_list)

Expected output:

[{'name':'Bill Cage','samplesubject':None},{'name':'Thomas Baszo','samplesubject':None}]
aysh
  • 423
  • 10
  • 17

0 Answers0