如何打印Python中列表中包含的字典的键和值

时间:2013-12-31 11:43:42

标签: python list dictionary

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]

上面给出的是我的python代码。 我想打印出学生列表中的所有数据,就像下面的例子一样。

  Lloyd
[90, 97, 75, 92]
[88, 40, 94]
[75, 90]

2 个答案:

答案 0 :(得分:2)

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 s in students:
    print s["name"]
    print s["homework"]
    print s["quizzes"]
    print s["tests"]

如果你想格式化一条线(花式):

>>>print "{:>10}".format("Lloyd")

会打印

      Lloyd

答案 1 :(得分:1)

你可以使用“For each”来轻松使用python:

示例:

items = [1,2,3,4]
for item in items:
    print item

这会打印列表中的所有数字

这是一个解决方案:

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

我希望这能帮到你!