vendredi 10 avril 2020

Python JSON " for loop - If different Dict key print something else" Youtube API

Im returning values from Youtube and when is just videos works fine. However, when I search for "gangnam style" the 6th vale is a channel not a video and creates an error. Does not have the key ['id']['videoId'] and instead have the key ['id']['channelId'] i tried to print the channel instead of creating an error, but still creates an error. this is the code that works fine if is just videos

import requests
import json

DEVELOPER_KEY = "xxxxxxxxxxxxxxxx"

name=(str(input("What would you like to search on youtube?: ")))

payload = {'part': 'snippet', 'key': DEVELOPER_KEY, 'order':'viewCount', 'q': name, 'maxResults': 10}
l = requests.Session().get('https://www.googleapis.com/youtube/v3/search', params=payload)    
resp_dict = json.loads(l.content)

with open('data.txt', 'a') as f:
  json.dump(resp_dict, f,indent=4, sort_keys=True,separators=(',', ': '))


for i in resp_dict['items']:
    print ("Title: ",i['snippet']['title']," Link: https://www.youtube.com/watch?v="+i['id']['videoId'])

I tried If statements after my "for loop" but im not getting nowhere, some examples:

if not any(d.get('id',None)== 'videoId' for d in resp_dict['items']):
       print ("Title: ",d['id']['channelId']) 
else:
       print ("Title: ",d['snipSpet']['title']," ----  Youtube Link: https://www.youtube.com/watch?v="+d['id']['videoId']) 

or

for key, value in resp_dict.keys() :
           if 'channelId' in value:
                pass
           else:
                print ("Title: ",i['snippet']['title']," ----  Youtube Link: https://www.youtube.com/watch?v="+i['id']['videoId'])

or

for i in resp_dict['items']:
    if not i['id']['videoId']:
        print ("Title: ",i['id']['channelId']
    else:
        print ("Title: ",i['id']['videoId'])

if someone could clarify what am I doing wrong I will appreciate

Aucun commentaire:

Enregistrer un commentaire