'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
{'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 1:[1]
Change the last line in your code to:
for item in response['items']:
print(item['statistics'])
Solution 2:[2]
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'].
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Albert Winestein |
| Solution 2 | mkrieger1 |
