循环遍历包含dicts的列表并以某种方式显示它

时间:2016-02-01 15:01:39

标签: python for-loop dictionary

这些是我用4个相同的键制作的3个词,但当然是不同的值。

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

我将dicts存储在列表中。

students = [lloyd, alice, tyler]

我想做的是遍历列表并按如下方式显示:

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

我在考虑for循环可以实现技巧for student in students:并且我可以将每个存储在一个空的dict current = {}中,但之后我就迷失了。我打算使用 getitem ,但我认为这不会奏效。

提前致谢

2 个答案:

答案 0 :(得分:15)

你可以这样做:

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)

答案 1 :(得分:5)

使用下面的循环显示所有学生数据没有硬编码键

# ... 
# 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))

祝你好运!