The codes:
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
In this code i want to make a nested dictionary in which the outer keys will be the roll no as what first element of every tuple of List Stu_det is( like UGM2018001) and then the nested keys will be the course code( like MA101 ) and then the element of each nested key will be a tuple or list which will have two elements, first element will be the course name( like Calculus ) and second element i want the grade mentioned ( like AB ) but accessing the grade is becoming problem ,how to access it or to get its index. I am unable to get Grade of subject after making roll no. and course code key.
Here's a way of doing it using defaultdict
module.
# 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')}})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.