Bugs That Bite
Published in

Bugs That Bite

TypeError: list indices must be integers or slices, not str

Problems iterating through and accessing JSON elements with Python

If you get this error while trying to access data in a JSON object check to see whether you are trying to access a list or a dictionary(dict).

Python lists look like this:

mylist = [“apple”, “banana”, “cherry”]

Python list:

A python dictionary looks like this:

car = {
"brand": "Ford",
"model": "Mustang",
"year": "1964"
}

If you have a json object like this with a list of cars and the attributes of each car are stored as a dict:

cars:
[{
"brand": "Ford",
"model": "Mustang",
"year": "1964"
},
{
"brand": "Jeep",
"model": "Gladiator",
"year": "2022"
}
]

If you are accessing a list, loop through the items in the list:

for item in json:
#do something

If you have a dict you can access the attribute you want using brackets:

item['name']

If you get the error:

TypeError: list indices must be integers or slices, not str

then you are probably trying to access an element in a dict, but first you have to iterate through your list.

So instead of this:

cars.brand

Do this:

for car in cars:
print (car['Brand'])

Teri Radichel

If you liked this story please clap and follow:

Medium: Teri Radichel or Email List: Teri Radichel
Twitter: @teriradichel or @2ndSightLab
Requests services via LinkedIn: Teri Radichel or IANS Research

© 2nd Sight Lab 2022

____________________________________________

Author:

Cybersecurity for Executives in the Age of Cloud on Amazon

Need Cloud Security Training? 2nd Sight Lab Cloud Security Training

Is your cloud secure? Hire 2nd Sight Lab for a penetration test or security assessment.

Have a Cybersecurity or Cloud Security Question? Ask Teri Radichel by scheduling a call with IANS Research.

Cybersecurity & Cloud Security Resources by Teri Radichel: Cybersecurity and Cloud security classes, articles, white papers, presentations, and podcasts

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store