How to get spotipy playlist results in list format

1.3k views Asked by At

I'm using spotipy to get a list of my playlists. I use

if token:
sp = spotipy.Spotify(auth=token)
playlists = sp.user_playlists(username)
for item in playlists['items']:
    id= item['uri']
    print id

This returns a list of playlist uri's that looks like

spotify:user:ultramusicofficial:playlist:0gvQoG7iMMz8L5Ltsa4lkT spotify:user:spotify:playlist:4Ha7Qja6HY3AgvNBgWz87p spotify:user:ministryofsounduk:playlist:7grWVkJDQpcBie8oqKP6hv

But there is something weird about the way it returns them. It's not a normal list and I can't seem to make it into one. If I use

print id[1]

It would return something like

p

p

p

I want to be able to do something like

print id[1]

and have it return

spotify:user:spotify:playlist:4Ha7Qja6HY3AgvNBgWz87p

I've tried joining it and splicing it in different ways, I've tried using it as a tuple, converting it to a string. Nothing works I'm clearly very unsure what to do. I feel like it's probably a simple and I'm just missing it. Any help would be appreciated thanks.

2

There are 2 answers

1
Psidom On BEST ANSWER

You are just printing the id, not gathering them into a list, so your id is the last item from the loop which is a single uri (a string). You can use a list comprehension to make a list out of the for loop:

id = [item['uri'] for item in playlists['items']]

Or start with an empty list and append the result to it:

id = []
for item in playlists['items']:
    id.append(item['uri'])
0
Stephen Rauch On

In your example id is a string. So id[1] is the second character, which is p