Reputation: 6967
I'm trying to get to grips with spotipy (again) I'm trying to return the artist, album, and track name from search by track title.
track = "Pretend we're dead"
results = sp.search(q="track:" + track, type="track")
for idx, artist, album, track in enumerate(results['tracks']['artist']['album']['items']):
print(idx, track['name'], track['artist'], album['album'])
Expected results:
I'm failing on deconstructing the list comprehension that are the results.
The error I'm getting is:
Traceback (most recent call last):
print(idx, track['name'], track['artist_id'])
KeyError: 'artist_id'
Upvotes: 2
Views: 983
Reputation: 3189
Looking at the docs, I see that the response is going to look like this (leaving out the boring parts):
{
"album": {}
"artists": [
{
"genres": [
"Prog rock",
"Grunge"
],
"href": "string",
"id": "string",
"images": [
{
"url": "https://i.scdn.co/image/ab67616d00001e02ff9ca10b55ce82ae553c8228\n",
"height": 300,
"width": 300
}
],
"name": "string",
"popularity": 0,
"type": "artist",
"uri": "string"
}
]
}
Looking at this, artists
is a key within the result, and it is a list of dictionaries, with each dict being a single artist for the track.
Using that info, this would be the way to refer to the first artist's id:
track["artists"][0]["id"]
If this isn't right, the trick to doing this is to just print(json.dumps(track, indent=3))
and look at the actual JSON you are receiving.
Upvotes: 3