我想在json文件中读取source
的所有id
,如下所示。
一个id
可以有两个来源,有时是零来源。
[
{
"trailers": {
"quicktime": [],
"youtube": [
{
"source": "source1",
"type": "Trailer",
"name": "Vf",
"size": "HD"
},
{
"source": "source2",
"type": "Trailer",
"name": "Vf",
"size": "HD"
}
],
"id": 57417
},
{
"trailers": {
"quicktime": [],
"youtube": [],
"id": 57418
}
]
我尝试了很多解决方案而且我停在了这个解决方案中,它也不起作用:
from itertools import chain
trailers = {}
for item in j:
if item['trailers']:
e = item['trailers']
for k,value in e.iteritems():
if k == "youtube":
for each_dict in value:
for innerk, innerv in each_dict.iteritems():
if innerk == "source" :
trailers = dict(trailers.items() , {'trailer' : 'None'}.iteritems())
else:
trailers = {'trailer' : 'None'}
修改: 我想看到这个结果:
57417, source1, source2
57418, None
你有什么建议吗?
答案 0 :(得分:0)
在YouTube上查找所有预告片:
trailers = {film['trailers']['id']: [source['source'] for source in film['trailers'].get('youtube', [])]
for film in j}
这会产生:
>>> {film['trailers']['id']: [source['source'] for source in film['trailers'].get('youtube', [])]
... for film in j}
{57417: ['source1', 'source2'], 57418: []}