Home > Software engineering >  Why is an expression like ['a']['b'] an error instead of getting values from a n
Why is an expression like ['a']['b'] an error instead of getting values from a n

Time:02-22

I am trying to get the subscriber count from a youtube channel using the youtube api. However the repsonse sends a nested dict with more information than just the subscriber count. Here is the code I tried using to solve the problem

from googleapiclient.discovery import build

api_key = 'my_key'

youtube = build('youtube', 'v3', developerKey=api_key)

request = youtube.channels().list(
    part='statistics',
    forUsername='pewdiepie'
    )

response = dict(request.execute())

print(response)
print(['items']['statistics'])

However I come up with this error

list indices must be integers or slices, not str

Here is the response I get from the youtube api

{'kind': 'youtube#channelListResponse', 'etag': 'b1tpsekLNgax8TyB0hih1FujSL4', 'pageInfo': {'totalResults': 1, 'resultsPerPage': 5}, 'items': [{'kind': 'youtube#channel', 'etag': 'gdAP8rVq0n-1Bj2eyjvac-CrtdQ', 'id': 'UC-lHJZR3Gqxm24_Vd_AJ5Yw', 'statistics': {'viewCount': '28147953019', 'subscriberCount': '111000000', 'hiddenSubscriberCount': False, 'videoCount': '4459'}}]}

CodePudding user response:

Change the last line in your code to:

for item in response['items']:
  print(item['statistics'])

CodePudding user response:

Based on the response you are posting here, if you want to know statistics from an item, you have to specify from which item you are trying to get statistics. items is a list, which means that you have to refer to it's elements by numerical index. It has a length as well, you can get by using len(response['items']). Now, let's say you want to get the subscriberCount from the first item in the list, in that case you can retrieve it with the following code:

if (len(response['items']) > 0):
    response['items'][0]['statistics']['subscriberCount']

CodePudding user response:

In order to access a value in a dictionary you actually have to include the dictionary in the expression.

['items']['statistics'] alone creates a list containing one string, 'items', and tries to access that list using the string 'statistics' as index. But this is bad, because list indices must be integers.

In order to access the key 'items' in the dictionary response, you can use response['items'].

Assuming this returns another, nested, dictionary, you can then access the key 'statistics' in that dictionary by using response['items']['statistics'].

  • Related