Python中的Retreive JSON键 [英] Retreive JSON Keys In Python
问题描述
我的目标是遍历classes
中的 每个 元素,并将classes
中的class
的值添加到新列表中.
My goal is to iterate through every element in classes
and add the value of class
in classes
into a new list.
JSON结构:
{
"images": [
{
"classifiers": [
{
"classes": [
{
"class": "street",
"score": 0.846
},
{
"class": "road",
"score": 0.85
}
]
}
]
}
]
}
在上述JSON示例中,新列表应包含:
In the above JSON example, the new list should contain:
{'street','road'}
我尝试遍历json_data['images'][0]['classifiers']['classes']
,并为每个list.append()
设置class
的值.
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)
我收到的TypeError
是:
TypeError: list indices must be integers or slices, not str
我从此TypeError
中得到的是,它尝试将字符串添加到列表中,但是list.append()
不接受字符串作为参数.我需要以某种方式将字符串转换为其他字符串.
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.
我的问题是我应该将字符串转换为什么,以便list.append()
接受它作为参数?
My question is what should I convert the string into so that list.append()
will accept it as a parameter?
推荐答案
第一个问题是classifiers
也是一个列表,因此您需要一个附加索引才能获取classes
.这将起作用:
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']:
第二,您希望将结果作为集合而不是列表,因此可以执行:return set(lst)
.请注意,集合是无序的,所以不要期望项目的顺序与列表的顺序相匹配.
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.
这篇关于Python中的Retreive JSON键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!