列表中字典遍历遇KeyError:如何正确处理嵌套结构的SCORE_3?
解决嵌套字典遍历中的KeyError问题
我懂你现在碰到的麻烦了——遍历嵌套字典时,SCORE_3可能不存在,直接用索引访问就会触发KeyError,而你用get()处理SCORE_1和SCORE_2的思路是对的,因为get()方法在键不存在时会返回None(或者你指定的默认值),不会抛出错误。
先回顾下你的原始数据结构:
mylist[0] = { '_id': ObjectId('aleatoryID'), 'created_at': datetime.datetime(2018, 3, 22, 11, 58, 23, 585000), 'person': { 'id': '00115500', 'scores': { 'SCORE_3': {'@score': '45'}, 'SCORE_1': 205, 'SCORE_2': 487 } } }
你的问题出在document['person']['scores']['SCORE_3'].get('@score')这部分:如果scores里没有SCORE_3这个键,直接用['SCORE_3']索引就会报错。正确的做法是对每一层嵌套都使用get()方法,并且给不存在的键设置默认的空字典,这样后续的get()调用就不会出错。
修改后的代码如下:
persons = [] for document in mylist: # 逐层获取,每一层都做防错处理 person = document.get('person', {}) # 若document中无'person',用空字典兜底 person_id = person.get('id') created_at = document.get('created_at') scores = person.get('scores', {}) # 若person中无'scores',用空字典兜底 score1 = scores.get('SCORE_1') score2 = scores.get('SCORE_2') # 处理SCORE_3的嵌套结构,先确保SCORE_3存在,不存在则用空字典 score3_dict = scores.get('SCORE_3', {}) score3 = score3_dict.get('@score') persons.append((person_id, created_at, score1, score2, score3))
如果你希望在键不存在时返回更友好的默认值(比如0或者"N/A"),可以给get()方法加上第二个参数:
score1 = scores.get('SCORE_1', 0) score3 = score3_dict.get('@score', 'N/A')
这样无论哪一层的键缺失,代码都能正常运行,不会抛出KeyError啦。
内容的提问来源于stack exchange,提问作者Pablo Brenner
相关产品推荐
相关产品推荐

