如何处理键不存在问题?解决Python字典合并的KeyError异常
解决字典列表合并时的KeyError问题
尝试合并两个数据结构(list1是字典列表,list2是字典)时触发KeyError,原因是list2中没有list1里的部分兄弟名称键,同时list1的brothers字段存在"N/A"值。需要给list1中的每个字典新增info键,值为对应兄弟在list2中的兴趣去重后排序的列表,没有匹配项则为空列表。
示例数据
list1 = [ {"Name":"Paul", "age": 34, "brothers": ["Sam","Cris","Jack"] } , {"Name":"Evan", "age": 14, "brothers": ["N/A"] } , {"Name":"Loki", "age": 4, "brothers": ["Thor"] } ] list2 = {"Sam":["ice_cream"], "Loki": ["cars"], "Jack": ["fruits","cars"], "Cris": ["ice_cream"] }
期望输出
[ {"Name": "Paul", "age": 34, "brothers": ["Sam","Cris","Jack"], "info": ["ice_cream", "fruits", "cars"]}, {"Name": "Evan", "age": 14, "brothers": ["N/A"], "info": []}, {"Name": "Loki", "age": 4, "brothers": ["Thor"], "info": []} ]
原错误代码
newList = [ {**d, "Ids": sorted(set(i for t in d["brothers"] for i in list2[t]))} for d in list1 ]
修正后的代码
new_list = [ {**d, "info": sorted(set( item for brother in d["brothers"] if brother != "N/A" for item in list2.get(brother, []) ))} for d in list1 ]
代码解释
- 避免KeyError:用
list2.get(brother, [])替代直接索引list2[brother],当兄弟名称不在list2中时返回空列表,不会触发异常。 - 过滤无效值:添加
if brother != "N/A"条件,跳过无意义的兄弟标识。 - 去重与排序:通过
set()自动去重,再用sorted()整理为有序列表,匹配输出要求。 - 键名修正:将原代码中的
"Ids"改为需求中的"info",对齐预期输出的键名。
内容的提问来源于stack exchange,提问作者Shinomoto Asakura
相关产品推荐
相关产品推荐

