Using Loops to Simplify Python Dictonaries -


i'm working on teaching myself python , i've been using codecademy tool that. i've understood basic premise of writing in keys dictionaries, realized adding keys dictionaries using loops easier, if had modify code later on, , each dictionary has identical values. however, cannot code return values want:

students = {"lloyd" : [], "alice" : [], "tyler" : []}  student in students:     student = {         "name" : [],          "homework" : [],          "quizzes" : [],          "tests" : []     }  print students 

but returns:

{'tyler': [], 'lloyd': [], 'alice': []} none 

how set up, that... it... worked, , had "name", "homework", "test", , "quiz" under students' names?

first of all, aren't returning anything. second, you're overwriting 'student' variable , never saving value you've created. should keep track, or modify dict go:

students = {"lloyd" : [], "alice" : [], "tyler" : []}  student in students:     students[student] = {  # notice change here         "name" : [],          "homework" : [],          "quizzes" : [],          "tests" : []     }  print students 

python supports classes sort of thing, too, though may not have gotten part of tutorials yet:

class student:      def __init__(self):          self.tests = []         self.quizzes = []         self.name = ""         self.homework = [] 

and can have behaviors associated student:

    def hw_average(self):          return sum(self.homework)/len(self.homework) # divide 0 if no homework, don't this.  

and can interact students:

jeff = student() jeff.name = "jeff" jeff.homework = [85, 92, 61, 78] jeff.hw_average()  # 79 

Comments