Need help regarding display


#1

The printing is not done in the order in which we have written the code. Example it should print name first, then homework, then quizzes and so on… but here the name is printed on the third line. Can you explain?


#2

Dictionaries are unordered, which means there is no information regarding order of insertion of data. We cannot predict the order that they will print out.

It is outside the parameters of this introductory course, but as you advance (past this course) you will begin to work with Python modules and learn to use the OrderedDict class of the collections module. Set this aside for now.

In the realm of what we do know by this point in the learning curve, we could use a list to create an ordered index and follow that order when outputting a dictionary.

items = ['name', 'homework', 'quizzes', 'tests']

Combining this with the students list,

for student in students: 
     for item in items: 
         print ("{:<8}: {}".format(item, student[item])) 

I made up placeholder dictionarys and this is the test output:

name    : Lloyd
homework: [50, 60, 80, 90, 70]
quizzes : [50, 50, 70, 60, 70]
tests   : [70, 80, 60]
name    : Alice
homework: [50, 60, 80, 90, 70]
quizzes : [50, 50, 70, 60, 70]
tests   : [70, 80, 60]
name    : Tyler
homework: [50, 60, 80, 90, 70]
quizzes : [50, 50, 70, 60, 70]
tests   : [70, 80, 60]

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.