我在使用 Spotipy 打印 Spotify 上的轨道信息时遇到问题。
我目前有以下代码:
import spotipy
import sys
import json
urn = 'spotify:track:450vazRH94IB21mom5FkN9'
sp = spotipy.Spotify()
track_info = sp.track(urn)
artist_name = track_info['album']['artists']
artist_name
它输出:
[{'external_urls': {'spotify': ' https://open.spotify.com/artist/0YWxKQj2Go9CGHCp77UOyy '}, 'href':'https://api.spotify.com/v1/artists/0YWxKQj2Go9CGHCp77UOyy ', 'id': '0YWxKQj2Go9CGHCp77UOyy', '名称':'棒极了', '类型': '艺术家', 'uri': 'spotify:艺术家:0YWxKQj2Go9CGHCp77UOyy'}]
当我尝试使用 Artist_name = track_info['album']['artists'] 并将 ['name] 添加到末尾时,如下所示:
artist_name = track_info['album']['artists']['name']
我收到此错误:
类型错误:列表索引必须是整数或切片,而不是 str
我不太确定为什么当它是一个字符串时它会这么说。
最佳答案
track_info['album']['artists']
是一个列表,您需要使用索引获取项目(list[0]
):
artist_name = track_info['album']['artists'][0]['name']
可以是多个艺术家。在这种情况下使用 list comprehension :
artist_names = [artist['name'] for artist in track_info['album']['artists']]
关于python - Blob : Printing Track Information,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43773138/