Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is an expression like ['a']['b'] an error instead of getting values from a nested dict?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Change the last line in your code to:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading