python - Blob : Printing Track Information

标签 python list python-3.x dictionary

我在使用 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/

相关文章:

python - SQLAlchemy:如何根据多个键自动递增?

c - 函数中的链表

python-3.x - 为什么重新分配给 __builtins__.dict 不会影响新字典对象的创建?

python - 如何从文件中读取数字(用空格分隔)?

python - sqlite 嵌套 for 循环错误

python - 无法计算两个日期之间的工作日?将 dtype ('<M8[ns]' ) 转换为 dtype ('<M8[D]' )?

python - 在不知道存在多少文件的情况下加载 py 文件并在目录的 for 循环中对类执行某些操作?

java - 简单的 Java 列表问题

python - 考虑到 p 在 python 中是素数,当我执行 p/p+1 + p+1/p 操作时出错

python - 为什么 'tornado.ioloop.IOLoop.instance().start()' 给我一个错误?