循环遍历包含dicts的列表并以某种方式显示它

Chr*_*ost 6 python dictionary for-loop

这些是我用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]
}
Run Code Online (Sandbox Code Playgroud)

我将dicts存储在列表中.

students = [lloyd, alice, tyler]
Run Code Online (Sandbox Code Playgroud)

我想做的是遍历列表并显示每个如下:

"""
student's Name: val
student's Homework: val
student's Quizzes: val
student's Tests: val
"""
Run Code Online (Sandbox Code Playgroud)

我在想一个for循环可以做到这一点for student in students:,我可以将每个存储在一个空的dict中,current = {}但之后我就迷失了.我打算使用getitem,但我认为这不会起作用.

提前致谢

Moh*_*uag 15

你可以这样做:

students = [lloyd, alice, tyler]

def print_student(student):
    print("""
        Student's name: {name}
        Student's homework: {homework}
        Student's quizzes: {quizzes}
        Student's tests: {tests}
    """.format(**student)) # unpack the dictionary

for std in students:
    print_student(std)
Run Code Online (Sandbox Code Playgroud)


And*_*yko 5

使用下面的循环显示没有硬编码键的所有学生数据:

# ... 
# Defining of lloyd, alice, tyler
# ...

students = [lloyd, alice, tyler]
for student in students:
    for key, value in student.items():
        print("Student's {}: {}".format(key, value))
Run Code Online (Sandbox Code Playgroud)

祝好运 !

  • 两点:首先,`iteritems`在现代Python中不再存在,但`items`在2和3中都有效,所以你不妨使用它.其次,虽然您没有对密钥进行硬编码,但这会丢失所需的输出顺序,因为dicts是无序的; 对我来说,"名字"在输出中排名第三,这感觉很奇怪. (2认同)