我正在嘗試使用 youtube api 從 youtube 頻道獲取訂閱者數量。但是,repsonse 會發送一個嵌套的字典,其中包含的資訊不僅僅是訂閱者數量。這是我嘗試用來解決問題的代碼
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'])
但是我想出了這個錯誤
list indices must be integers or slices, not str
這是我從 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'}}]}
uj5u.com熱心網友回復:
將代碼中的最后一行更改為:
for item in response['items']:
print(item['statistics'])
uj5u.com熱心網友回復:
根據您在此處發布的回復,如果您想了解某個專案的統計資訊,則必須指定您嘗試從哪個專案獲取統計資訊。items是一個串列,這意味著您必須通過數字索引來參考它的元素。它也有長度,您可以使用len(response['items'])來獲得。現在,假設您想從串列中的第一項獲取subscriberCount,在這種情況下,您可以使用以下代碼檢索它:
if (len(response['items']) > 0):
response['items'][0]['statistics']['subscriberCount']
uj5u.com熱心網友回復:
為了訪問字典中的值,您實際上必須在運算式中包含字典。
['items']['statistics']單獨創建一個包含一個字串的串列'items',并嘗試使用該字串'statistics'作為索引來訪問該串列。但這很糟糕,因為串列索引必須是整數。
為了訪問'items'字典中的鍵response,您可以使用response['items'].
假設這會回傳另一個嵌套的字典,然后您可以使用 訪問該'statistics'字典中的鍵response['items']['statistics']。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/430539.html
上一篇:tkinter/datetime/weekday/dictionary/型別錯誤:strptime()引數1必須是str,而不是entry
