簡體   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