繁体   English   中英

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

[英]How to print keys and values of a dictionary which is contained in a list in 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]

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

  Lloyd
[90, 97, 75, 92]
[88, 40, 94]
[75, 90]
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

您可以使用“ 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']

希望对您有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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