使用词典时多次打印输出

时间:2015-01-04 17:15:19

标签: python

我试图运行这个Python代码:

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 student in students:
    for key in lloyd:
        print lloyd[key]
    for key in alice:
        print alice[key]
    for key in tyler:
        print tyler[key]

收到的输出是打印字典的关键数据的多个值。请建议是否有任何我可以更改的内容,以及如何使用for循环仅打印单个关键数据,例如测试标记。

3 个答案:

答案 0 :(得分:1)

对于像'tests'这样的个人密钥,您只需使用索引:

>>> for student in students:
...    print student['tests']
... 
[75.0, 90.0]
[89.0, 97.0]
[100.0, 100.0]

答案 1 :(得分:0)

使用print语句打印学生姓名和测试标记。

for student in students:
    print "Name:%s\nTests:%s\n"%(student["name"], student["tests"])

输出:

Name:Lloyd
Tests:[75.0, 90.0]

Name:Alice
Tests:[89.0, 97.0]

Name:Tyler
Tests:[100.0, 100.0]

答案 2 :(得分:0)

直接从学生词典中按键tests检索每个值:

for student in students:
    print student["tests"]