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)
使用下面的循环显示没有硬编码键的所有学生数据:
# ...
# 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)
祝好运 !