Reputation: 1972
My goal is to iterate through every element in classes
and add the value of class
in classes
into a new list.
JSON Structure:
{
"images": [
{
"classifiers": [
{
"classes": [
{
"class": "street",
"score": 0.846
},
{
"class": "road",
"score": 0.85
}
]
}
]
}
]
}
In the above JSON example, the new list should contain:
{'street','road'}
I tried to iterate over json_data['images'][0]['classifiers']['classes']
and for each one list.append()
the value of class
.
list = list()
def func(json_data):
for item in json_data['images'][0]['classifiers']['classes']:
list.append(item['class'])
return(list)
I am receiving a TypeError
which is:
TypeError: list indices must be integers or slices, not str
What I am getting from this TypeError
is that it attempts to add a string to the list but list.append()
does not accept a string as a paramet. I need to somehow convert the string into something else.
My question is what should I convert the string into so that list.append()
will accept it as a parameter?
Upvotes: 1
Views: 255
Reputation: 13175
The first issue is that classifiers
is also a list, so you need an additional index to get at classes
. This will work:
for item in json_data['images'][0]['classifiers'][0]['classes']:
Second, you want the result as a set not a list, so you can do: return set(lst)
. Note that sets are unordered, so don't expect the ordering of items to match that of the list.
Upvotes: 3