代码:
Cour_det = [("MA101","Calculus"),("PH101","Mechanics"),("HU101","English")];
Stu_det = [("UGM2018001","Rohit Grewal"),("UGP2018132","Neha Talwar")];
Grades = [("UGM2018001", "MA101", "AB"),("UGP2018132", "PH101", "B"),
("UGM2018001", "PH101", "B")];
Cour_det = sorted(Cour_det, key = lambda x : x[0]);
Stu_det = sorted(Stu_det, key = lambda x : x[0]);
Grades = sorted(Grades, key = lambda x : x[1]);
Grades = sorted(Grades, key =lambda x : x[0]);
B={}
#code by which i tried to add grade to nested list
for i in range(len(Stu_det)):
for j in range(len(Cour_det)):
B[Stu_det[i][0]][Cour_det[j][0]]=(Cour_det[j][1],Grades[][])
#here i am stuck on how to access grade of the course that i am adding
#it should look like this
B={"UGM2018001":{"MA101":("Calculus","AB'),"PH101":("Mechanics","B")}}
#above list for roll no UGM2018001,similarly other roll no.s as keys and
#course code can be keys of nested list for those roll no.s
在这段代码中,我想创建一个嵌套字典,其中外键将是roll no,因为List Stu_det的每个元组的第一个元素是(类似于UGM2018001),然后是嵌套键将是课程代码(像MA101 ),然后每个嵌套键的元素将是一个元组或列表,它将有两个元素,第一个元素将是课程名称(喜欢微积分< / strong>)和第二个元素我想要提到的等级(像AB )但访问成绩正在成为问题,如何访问它或获取其索引。制作卷号后,我无法获得成绩等级。和课程代码密钥。
答案 0 :(得分:0)
以下是使用defaultdict
模块执行此操作的方法。
# load library
from collections import defaultdict
# convert to dictionary as this will help in mapping course names
Cour_det = dict(Cour_det)
Stu_det = dict(Stu_det)
# create a dictionary for grades
grades_dict = defaultdict(list)
for x in Grades:
grades_dict[x[0]].append(x[1:])
# create a new dict to save output
new_dict = defaultdict(dict)
# loop through previous dictionary and replace course codes with names
for k,v in grades_dict.items():
for val in v:
temp = list(val)
temp[0] = Cour_det[temp[0]]
new_dict[k].update({val[0]: tuple(temp)})
# print output
print(new_dict)
defaultdict(dict,
{'UGM2018001': {'MA101': ('Calculus', 'AB'),
'PH101': ('Mechanics', 'B')},
'UGP2018132': {'PH101': ('Mechanics', 'B')}})