[英]How to print dictionary from list “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]
}
students = ["lloyd","alice","tyler"]
#Accessing Dictionary from List
print students[0]['name']
预期结果是:劳埃德
每当我运行上述代码时,都会出现此错误,
===============================================
Traceback (most recent call last):
File "python", line 30, in <module>
TypeError: string indices must be integers
===============================================
任何帮助将不胜感激。
这是因为学生仅包含字符串[“ lloyd”,“ alice”,“ tyler”]
print students[0]
>> "lloyd"
也许您想这样做:
students = [lloyd]
然后
print students[0]['name']
应该管用
您可能希望将字典而不只是字符串名称放在列表中。
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 "}
tyler = {"name": "Tyler "}
students = [lloyd, alice, tyler]
print students[0]['name']
运行以下命令:
print students[0]
它将给出您想要的输出。
目前, students
只是一个字符串列表。 因此, students[0]
的值是字符串'lloyd'
,与您创建的名称为lloyd
的字典不同。
我想您希望students
成为字典列表。 下面,我展示了如何执行此操作,并为alice
和tyler
创建了空字典。 然后,简单地将引号从您的students
声明中students
以存储字典,而不是存储具有相同名称的字符串,最后一行就可以了。
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"}
tyler = {"name": "Tyler"}
students = [lloyd,alice,tyler]
print students[0]['name']
这使:
Lloyd
您没有使用顶部定义的字典lloyd。 当使用students = [“ lloyd”,“ alice”,“ tyler”]创建列表时,您将使用字符串“ lloyd”。 因此,students [0]返回此字符串而不是dict。
您需要使用学生= [劳埃德,阿里斯,泰勒]。 您可能还想为alice和tyler创建一个字典。
您尝试过的几乎是正确的。 因为“字符串索引必须是整数”,所以出现错误。 因此,您可以在python( python-eval-method )中使用eval()方法。
试试下面的代码
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
students = ["lloyd","alice","tyler"]
#Accessing Dictionary from List
print eval(students[0])['name']
会工作的
您的students
列表仅包含str
对象。
print students[0]
>> "lloyd"
如您所见,我们得到了str
对象类型。
您应该使用此用法并删除引号来解决此问题:
students = [lloyd]
print students[0]['name']
完成! :)
最好使用get
方法用于dict用法:
print students[0].get('name')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.