For the Record


#1

having huge problems:
Code:

lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

students = [lloyd, alice, tyler]
for key in students:
    print students["name"]
    print students["homework"] 
    print students["quizzes"]
    print students["tests"]

error: Traceback (most recent call last):
File "python", line 22, in
TypeError: list indices must be integers, not str


#2

figured it out
also can some one explain why its student["name"] not students["name"]


#3

where? Also could you give some information on what the problem was? And your for loop seems to be not that effective.


#4

i changed print students["name"] etc to print student["name"] and it worked
additionally no wonder the code is not effective as I am a complete beginner


#5

If would only make sense if you'd changed "key" to student e.g.

for student in students:
    print student["name"]
    print student["homework"] 
    print student["quizzes"]
    print student["tests"]

instead of:

for key in students:
    print students["name"]
    print students["homework"] 
    print students["quizzes"]
    print students["tests"]

Explanation: students is a list containing students, namely the student dictionaries llyod, alice and tyler. So you can either use students[i] to access them e.g. students[0] is lloyd or you can loop through all the entries of the list using a for in loop. But using strings inside the brackets doesn't seem to be allowed for lists.
On the other hand if you use my first code snippet student or in your case key is one of the student dictionaries and dictionaries can have strings in their brackets. So tyler["name"] would give you name aso.

And forget about the inefficiency of the for loop, first of all I'm well aware that this is a beginners forum so no attack on you intended in any way and the other thing is that I made a mistake myself and the for loop should be ok. Although I'm pretty sure that there is an easier way then using 4 print statement and even if it is another list and another loop :slightly_smiling:


#6

Hmmm, this is not working for me :frowning:


#7

Found it! The code looks like this. There should be a shorter way though...


#8

Hi,

I got it to work with the following:

Hope this helps. Let me know if it does! Thanks,


#9

Hi the short way could be like that...

for student in students:
    print student["name"]
    print student["homework"]
    print student["quizzes"]
    print student["tests"]

But if you do it like that you should change the array of students like that

from

students = ["lloyd", "alice", "tyler"]

To 

students = [lloyd, alice, tyler]