python - How to use nested *Nested Dictionaries* -
so code neatest if able nest dictionaries. questions are:
- are nested dictionaries real thing? (is possible?)
- how set them up?
- how value of sub-dictionary key?
here of code trying use. please tell me correct format is, , might wrong... thanks!
student.alice = { student.alice.math = { 'math1'= 100 'math2'= 98 'math3' = 89 'math4' = 91 'math5' = 77 'math6' = 90 'math7' = 82 'math8' = 100 'math9' = 79 'math10' = 100 } student.alice.english = { 'english1' = 100 'english2' = 97 'english3' = 98 'english4' = 88 'english5' = 94 'english6' = 95 'english7' = 98 'english8' = 82 'english9' = 84 'english10' = 99 } student.alice.science = { 'science1' = 78 'science2' = 89 'science3' = 88 'science4' = 92 'science5' = 92 'science6' = 91 'science7' = 93 'science8' = 88 'science9' = 99 'science10' = 87 } student.alice.french = { 'french1' = 100 'french2' = 100 'french3' = 99 'french4' = 104 'french5' = 103 'french6' = 97 'french7' = 94 'french8' = 93 'french9' = 75 'french10' = 93 } }
nested dictionaries going lead world of pain in future. highly suggest learning object oriented programming, , classes. below not-working-but-headed-in-the-right-direction example.
class assignment(dict): '''this inherits dict, student key, grade score''' def __init__(self, name, max_score): self.name = name self.max_score = max_score self.grades = {} # used store students , grades. def __getitem__(self, student): # we're overriding getitem, because default 0 if student doesn't turn in work if student in self: return dict.__getitem__(self, student) return 0.0 class gradebook(dict): '''a gradebook dict of assignments''' def get_max_score(self): return sum(assignment.max_score assignment in self.values()) def get_percentage(self, student): return 100.0 * sum(assignment[student] assignment in self.values()) / self.get_max_score() class course(object): def __init__(self, name, time, teacher, students): self.name = name self.time = time # can teach multiple courses same name, not @ same time self.teacher = teacher self.students = students self.grade_book = gradebook() def add_assignment(self, assignemnt): self.grade_book.append(assignment) class person(object): def __init__(self, first, last): self.first = first self.last = last def __repr__(self): return '<{} {} {}>'.format(self.__class__.__name__, self.first, self.last) class student(person): '''a student person...''' class teacher(person): '''a teacher person...'''
Comments
Post a Comment