[英]how do i call dictionary values from within a list of dictionaries ?
我正在尝试与codeacademy学习python。 作业是制作3本书(每个学生),然后列出3本书的清单。 然后,我应该打印出列表中的所有数据。
我试图用与字典本身相同的方式(lloyd [values])来调用值,但随后它说值未定义为o_O。 我也尝试过“打印名称”,但是错误消息是我没有打印出其中一个值。
我非常感谢您的帮助。
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 names in students:
print lloyd[values]
如果要打印每个学生的所有信息,则必须遍历学生和存储在词典中的值:
students = [lloyd, alice, tyler]
for student in students:
for value in student:
print value, "is", student[value]
但是请注意,字典没有顺序,因此值的顺序可能不是您想要的。 在这种情况下,使用值的名称作为字符串作为键分别打印它们:
for student in students:
print "Name is", student["name"]
print "Homework is", student["homework"]
# same for 'quizzes' and 'tests'
最后,您还可以使用pprint
模块“漂亮地打印”学生词典:
import pprint
for student in students:
pprint.pprint(student)
您可以简单地打印字典的值:
for names in students:
print names #names are the dictionaries
如果只想打印名称,请使用name
键:
for student in students:
print student['name']
我建议改用namedtuple来提高可读性和可伸缩性:
from collections import namedtuple
Student = namedtuple('Student', ['name', 'hw', 'quiz', 'test'])
Alice = Student('Alice', herHWLst, herQuizLst, herTestLst)
Ben = Student('Ben', hisHWLst, hisQuizLst, hisTestLst)
students = [Alice, Ben]
for student in students:
print student.name, student.hw[0], student.quiz[1], student.test[2]
#whatever value you want
如果您确实想创建大量词典,则可以通过以下代码与上面的代码一起阅读:
for student in students:
name = student['name']
homeworkLst = student['homework']
# get more values from dict if you want
print name, homeworkLst
在Python中,访问字典的速度非常快,但是创建字典的速度和效率可能不一样。 在这种情况下,namedtuple更实用。
因此, students
是词典列表。 然后你想要
for student in students:
print student['name']
同样,当您要在字典中调用键时,也必须将键名称用引号引起来,并使用字符串: alice[homework]
不起作用,因为Python认为homework
是变量。 您需要alice['homework']
代替。
因此,要很好地查看所有信息,您可以
for student in students:
for field in student.keys():
print "{}: {}".format(field, student[field])
您可以尝试使格式更好,例如,首先打印名称,在每个新学生之间插入新行,等等。
这就是我在Codeacademy上解决我的问题的方式。 希望有人发现这对学生中的学生有帮助:
print student['name']
print student['homework']
print student['quizzes']
print student['tests']
这就是我让他们接受的东西。
for name in students:
print name["name"]
print name["homework"]
print name["quizzes"]
print name["tests"]
这也可以,但是他们不会接受。
for name in students:
print name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.