如何使用Python将多个列表转换为指定结构的嵌套字典
将列表转换为嵌套字典的Python实现
给定以下Python列表:
subjects = ['Chem', 'Phy', 'Math'] students = ['Joy', 'Agatha', 'Mary', 'Frank', 'Godwin', 'Chizulum', 'Enoc', 'Chinedu', 'Kenneth', 'Lukas'] math = [76,56,78,98,88,75,59,80,45,30] phy = [72,86,70,98,89,79,69,50,85,80] chem = [75,66,77,45,83,75,59,40,65,90]
需要转换为如下结构的嵌套字典:
{ 'math': {'Joy':76, 'Agatha':56, 'Mary':78, ...}, 'phy': {'Joy':72, 'Agatha':86, 'Mary':70, ...}, 'chem': {'Joy':75, 'Agatha':66, 'Mary':77, ...} }
下面是几种可行的实现方法:
方法一:手动构建(直观易懂)
先分别为每个科目生成学生-分数的字典,再组合成外层嵌套字典:
# 生成各科目对应的学生分数字典 math_dict = {stu: sc for stu, sc in zip(students, math)} phy_dict = {stu: sc for stu, sc in zip(students, phy)} chem_dict = {stu: sc for stu, sc in zip(students, chem)} # 组合成最终结果 final_dict = { 'math': math_dict, 'phy': phy_dict, 'chem': chem_dict } print(final_dict)
方法二:批量处理(适配多科目场景)
如果后续要添加更多科目,手动逐个构建效率低,可以先建立科目与分数列表的映射,再批量生成:
# 建立科目名称和对应分数列表的映射 subject_map = { 'math': math, 'phy': phy, 'chem': chem } # 嵌套推导式批量生成字典 final_dict = {sub: dict(zip(students, scores)) for sub, scores in subject_map.items()} print(final_dict)
方法三:一行简洁实现
利用dict()和zip()的组合,直接完成转换:
final_dict = { 'math': dict(zip(students, math)), 'phy': dict(zip(students, phy)), 'chem': dict(zip(students, chem)) } print(final_dict)
说明
zip(students, 分数列表)会把学生姓名和对应的分数按顺序一一配对;dict()函数可以直接将这些配对的元组转换为键值对字典;- 外层字典则将科目名称作为键,对应的学生分数字典作为值。
内容的提问来源于stack exchange,提问作者Ojo Joseph
相关产品推荐
相关产品推荐

