Issue
This Content is from Stack Overflow. Question asked by TUSK ACT 4
i want to run this code
listf = [
{"name":"akram"}
]
for i in listf:
print(listf["name"])
and this error happened:
line 5, in <module>
print(listf["name"])
TypeError: list indices must be integers or slices, not str
but in another code from another user :
students = [
{"name": "Hermione", "house": "Gryffindor", "patronus": "Otter"},
{"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
{"name": "Ron", "house": "Gryffindor", "patronus": "Jack Russell terrier"},
{"name": "Draco", "house": "Slytherin", "patronus": None},
]
for student in students:
print(student["name"], student["house"], student["patronus"], sep=", ")
and it run normal
Solution
If you take a look at the second example they accessed students
dictionaries via student
not students
. Let me show it to you differently:
for st in students: # Here I changed student by st
print(st["name"], st["house"], st["patronus"], sep=", ")
Try this will help you make the distinction in your code:
listf = [
{"name":"akram"}
]
for i in listf:
print(i)
Output:
{"name":"akram"}
See? Here i
is the dictionary. Here’s how you should access it:
listf = [
{"name":"akram"}
]
for i in listf:
print(i["name"])
This Question was asked in StackOverflow by TUSK ACT 4 and Answered by Diurnambule It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.