user1476390 user1476390 - 2 months ago 4
Python Question

how do i call dictionary values from within a list of dictionaries ?

i am trying to learn python with codeacademy.
the assignment was make 3 dictionaries (for each student) and then make a list of the 3 dictionaries. then, i am supposed to print out all the data in the list.

i tried to call out the values the same way i used for a dictionary by itself (lloyd[values]), but then it says that values is not defined o_O. I have also tried to 'print names' but then the error message is that i didn't print out one of the values.

i'd appreciate your help very much.

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 names in students:
print lloyd[values]

Answer

If you want to print all the information for each student, you have to loop over the students and the values stored in the dictionaries:

students = [lloyd, alice, tyler]
for student in students:
    for value in student:
        print value, "is", student[value]

Note, however, that dictionaries are not ordered, so the order of the values might not be the way you want it. In this case, print them individually, using the name of the value as a string as key:

for student in students:
    print "Name is", student["name"]
    print "Homework is", student["homework"]
    # same for 'quizzes' and 'tests'

Finally, you could also use the pprint module for "pretty-printing" the student dictionaries:

import pprint
for student in students:
    pprint.pprint(student)
Comments