【问题标题】:Spotipy: Printing Track InformationSpotipy:打印曲目信息
【发布时间】:2017-10-02 01:23:32
【问题描述】:

我在使用 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:artist:0YWxKQj2Go9CGHCp77UOyy'}]

当我尝试使用 artist_name = track_info['album']['artists'] 并将 ['name] 添加到末尾时,如下所示:

artist_name = track_info['album']['artists']['name']

我收到此错误:

TypeError: 列表索引必须是整数或切片,而不是 str

我不太确定为什么它是一个字符串时会这样说。

【问题讨论】:

    标签: python list python-3.x dictionary


    【解决方案1】:

    track_info['album']['artists']是一个列表,需要使用索引(list[0])来获取item:

    artist_name = track_info['album']['artists'][0]['name']
    

    它可以是多个艺术家。在这种情况下使用list comprehension:

    artist_names = [artist['name'] for artist in track_info['album']['artists']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      • 2017-02-03
      • 2016-08-10
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多