【发布时间】:2016-05-10 02:14:21
【问题描述】:
这些是我用 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]
}
我将字典存储在一个列表中。
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: 并且我可以将每个循环存储在一个空的字典中 current = {} 但在那之后我就迷路了。我打算使用 getitem,但我认为这行不通。
提前致谢
【问题讨论】:
-
那些字典基本上是穷人的课。如果您熟悉 Python 的类和面向对象的编程,您可以使用
transcript方法创建一个Student类(或者直接覆盖__str__魔术方法)。然后,您只需在for student in students:循环中打印student.transcript()或str(student)。 (如果下一个处理该数据的函数或程序需要dict,请将数据保留在dict中。) -
ChrisSlightGhost 按键打印顺序对您来说很重要吗?
标签: python for-loop dictionary