python - 创建嵌套子字典 python

标签 python dictionary collections pymongo key-value

我的列表中有一些不同类型的学生姓名和每种类型的分数。 例如:

students_exam_names = [exam_name1, exam_name2, exam_name3]
students_exam_score = [exam_score1, exam_score2, exam_score3]
students_quiz_names = [quiz_name1, quiz_name2]
students_quiz_score = [quiz_score1, quiz_score2]
students_homework_names = [homework_name1, homework_name2, homework_name3, homework_name4]
students_homework_score = [homework_score1, homework_score2, homework_score3, homework_score4]

对于所有三个都类似,如下所示。

我想以嵌套字典的形式获得详细信息,如下所示:

details = {'students_exam':{
    'exam_name1':exam_score1,
    'exam_name2':exam_score2,
    'exam_name3':exam_score3
},
'students_quiz':{
    'quiz_name1': quiz_score1,
    'quiz_name2': quiz_score2
},
'students_homework':{
    'homework_name1': homework_score1,
    'homework_name2': homework_score2,
    'homework_name3': homework_score3,
    'homework_name4': homework_score4,
}

每个学生类型的长度不同。我尝试以字典列表的形式获取它,如下所示,但无法进一步。

students_exam = {}

for i in range(len(students_exam_names)):
  students_exam[students_exam_names[i]] = students_exam_score[i]

最佳答案

定义输入时,不要忘记使用 ':

students_exam_names = ['exam_name1', 'exam_name2', 'exam_name3']
students_exam_score = ['exam_score1', 'exam_score2', 'exam_score3']
students_quiz_names = ['quiz_name1', 'quiz_name2']
students_quiz_score = ['quiz_score1', 'quiz_score2']
students_homework_names = ['homework_name1', 'homework_name2', 'homework_name3', 'homework_name4']
students_homework_score = ['homework_score1', 'homework_score2', 'homework_score3', 'homework_score4']

然后,只需使用 zip 函数即可:

details = {'students_exam': dict(zip(students_exam_names, students_exam_score)),
           'students_quiz': dict(zip(students_quiz_names, students_quiz_score)),
           'students_homework': dict(zip(students_homework_names, students_homework_score))}

输出为:

{'students_exam': {'exam_name1': 'exam_score1', 'exam_name2': 'exam_score2', 'exam_name3': 'exam_score3'}, 'students_quiz': {'quiz_name1': 'quiz_score1', 'quiz_name2': 'quiz_score2'}, 'students_homework': {'homework_name1': 'homework_score1', 'homework_name2': 'homework_score2', 'homework_name3': 'homework_score3', 'homework_name4': 'homework_score4'}}

关于python - 创建嵌套子字典 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71423404/

相关文章:

python - Django:在下拉列表中显示字典的值

Java 7 - "Comparison method violates its general contract!"

Java 8 lambda 表达式 : Mapping a Stream to type Integer and then calling sum() won't compile

python - 在 CPython 3.6 中获取字典中的第一个和第二个值

python - 在运行时添加 gRPC 服务程序并为客户端提供接口(interface)

python - 子进程模块输入换行符

python - 神经学习的准确性变为 NaN( tensorflow )

python - 给定所有两个连续单词出现的文本计数

javascript - 性能: findIndex vs Array.原型(prototype).map

python - 如何检测碰撞? pygame