We Are Going To Discuss About TypeError: list indices must be integers or slices, not str – While accessing element of list. So lets Start this Python Article.
TypeError: list indices must be integers or slices, not str – While accessing element of list
- How to solve TypeError: list indices must be integers or slices, not str – While accessing element of list
First of all, you have taken the dictionary mistakenly with ' ' which indicates
'{"id": 9, "name": "Foo"}'
as a string. Remove quotation marks and iterate the list. Assume the list size is fixed to one dictionary list.a = [{"id":9, "name":"Foo"}] id = a[0]['id'] print(id)
Let's your list be long likea = [{"id": 9, "name": "Foo"}, {"id": 10, "name": "Bar"},{"id": 11, "name": "FooBar"}]
Then get id by using loopfor l in a: print(l['id'])
- TypeError: list indices must be integers or slices, not str – While accessing element of list
First of all, you have taken the dictionary mistakenly with ' ' which indicates
'{"id": 9, "name": "Foo"}'
as a string. Remove quotation marks and iterate the list. Assume the list size is fixed to one dictionary list.a = [{"id":9, "name":"Foo"}] id = a[0]['id'] print(id)
Let's your list be long likea = [{"id": 9, "name": "Foo"}, {"id": 10, "name": "Bar"},{"id": 11, "name": "FooBar"}]
Then get id by using loopfor l in a: print(l['id'])
Solution 1
First of all, you have taken the dictionary mistakenly with ‘ ‘ which indicates '{"id": 9, "name": "Foo"}'
as a string. Remove quotation marks and iterate the list. Assume the list size is fixed to one dictionary list.
a = [{"id":9, "name":"Foo"}]
id = a[0]['id']
print(id)
Let’s your list be long like
a = [{"id": 9, "name": "Foo"}, {"id": 10, "name": "Bar"},{"id": 11, "name": "FooBar"}]
Then get id by using loop
for l in a:
print(l['id'])
Original Author mhhabib Of This Content
Solution 2
you are storing the dictionary as a string so the error you are getting is expected.
If you want to access the id in the dictionary then store it as the dictionary itself.
To access the id value you can check the below code
a=[{"id":9,"name":"Foo"}]
b=a[0]['id']
print(b)
Original Author alimi sumanth Of This Content
Solution 3
list have not attribute allows key and value.
then you can try with dictonary.
Original Author Mayank Vachhani Of This Content
Solution 4
I was solve this by the following
-
Passing
[{"id":9,"name":"Foo"}]
instead of['{"id":9,"name":"Foo"}']
which can done by removingjson_encode()
while sending data to Flask Application. In my case was from Laravel / PHP. -
By accessing element using
a[0]['id']
as pointed by @mhhabib
Original Author Mayank Vachhani Of This Content
Conclusion
So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.