如何解决检查嵌套字典中是否存在密钥时发生密钥错误
我需要检查教授钥匙是否存在'samplesubject'
。
由于samplesubject
不在主词典searchtest
中,因此出现键错误。
示例字典在下面
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','_source': {'name': 'Accounting 101','professor': {'department': 'finance','email': 'baszot@onuni.com','facutly_type': 'part-time','name': 'Thomas Baszo'},'room': 'E3','students_enrolled': 27}}]
代码在下面
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)
预期输出:
[{'name':'Bill Cage','samplesubject':None},{'name':'Thomas Baszo','samplesubject':None}]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。