简体   繁体   中英

Looping through a list that contains dicts and displaying it a certain way

These are 3 dicts I made each with the 4 same keys but of course different values.

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]
}

I stored the dicts in a list.

students = [lloyd, alice, tyler]

What I'd like to do is loop through the list and display each like so:

"""
student's Name: val
student's Homework: val
student's Quizzes: val
student's Tests: val
"""

I was thinking a for loop would do the trick for student in students: and I could store each in a empty dict current = {} but after that is where I get lost. I was going to use getitem but I didn't think that would work.

Thanks in advance

You can do this:

students = [lloyd, alice, tyler]

def print_student(student):
    print("""
        Student's name: {name}
        Student's homework: {homework}
        Student's quizzes: {quizzes}
        Student's tests: {tests}
    """.format(**student)) # unpack the dictionary

for std in students:
    print_student(std)

Use loop below to display all students data without hardcoding keys :

# ... 
# Defining of lloyd, alice, tyler
# ...

students = [lloyd, alice, tyler]
for student in students:
    for key, value in student.items():
        print("Student's {}: {}".format(key, value))

Good Luck !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM