I’m working with a music streaming API and getting back a list of dictionaries with artist information. I need to pull out just the URI values from each dictionary in the response.
Loop through each dict and split the uri string. Try this: ids = [item['uri'].split(':')[-1] for item in music_data] then print with print(' '.join(f'[{id}]' for id in ids)). The split(‘:’) breaks up the spotify:artist:id and [-1] grabs the last part.
I’ve dealt with similar Spotify API responses - regex works better for pulling IDs from URIs. Try this: import re then ids = [re.search(r'spotify:artist:(.+)', item['uri']).group(1) for item in music_data]. Print it with print(' '.join(f'[{id}]' for id in ids)). The regex grabs everything after ‘spotify:artist:’ so you get the ID directly. Way more solid than splitting since it actually matches the URI format and won’t break if there’s random colons in the ID. I always use this with external APIs since the data format can be inconsistent.
Your syntax is wrong - you’re trying to use a string as an index. You need to loop through the list first, then grab the uri key from each dictionary. Here’s what works for me with similar API responses:
for artist in music_data:
uri = artist['uri']
artist_id = uri.split(':')[2] # Split on colon and take the third element
print(f'[{artist_id}]', end=' ')
This shows exactly what’s happening at each step. The URI format is always spotify:artist:ID so splitting on the colon gives you three parts and the ID is at index 2. You could also use uri.split(':')[-1] to get the last part, but I like being explicit about the expected structure with external APIs.