0

I would like to read all source for an id in a json file that looks like this. One id can have two sources, sometimes zero sources.

[ 
    {
        "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
        }
] 

I tried many solutions and I stopped in this one , and it doesn't work also :

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'}

Edit : I would like to see this result :

57417, source1, source2
57418, None

Do you have suggestions ?

4m1nh4j1
  • 4,289
  • 16
  • 62
  • 104

1 Answers1

0

Finding all trailers on YouTube:

trailers = {film['trailers']['id']: [source['source'] for source in film['trailers'].get('youtube', [])] 
            for film in j}

This produces:

>>> {film['trailers']['id']: [source['source'] for source in film['trailers'].get('youtube', [])] 
...             for film in j}
{57417: ['source1', 'source2'], 57418: []}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • @SteveJessop: Nested list comprehension there. But I was tripping over what is a list and what is a dictionary there first. All working now. – Martijn Pieters Dec 18 '13 at 18:29