How to get specific URI values from Python list when working with music API

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.

Here’s what my API response looks like:

music_data = [
    {'external_urls': {'spotify': 'https://open.spotify.com/artist/7XB93KLm2VqzHRPiVczEU2'}, 'href': 'https://api.spotify.com/v1/artists/7XB93KLm2VqzHRPiVczEU2', 'id': '7XB93KLm2VqzHRPiVczEU2', 'name': 'Jackson Miles', 'type': 'artist', 'uri': 'spotify:artist:7XB93KLm2VqzHRPiVczEU2'},
    {'external_urls': {'spotify': 'https://open.spotify.com/artist/2M84eBRlVxd4v4YnccZlvs'}, 'href': 'https://api.spotify.com/v1/artists/2M84eBRlVxd4v4YnccZlvs', 'id': '2M84eBRlVxd4v4YnccZlvs', 'name': 'Sarah Connor', 'type': 'artist', 'uri': 'spotify:artist:2M84eBRlVxd4v4YnccZlvs'},
    {'external_urls': {'spotify': 'https://open.spotify.com/artist/9Cv3GYUzNM11yYGQslMOkp'}, 'href': 'https://api.spotify.com/v1/artists/9Cv3GYUzNM11yYGQslMOkp', 'id': '9Cv3GYUzNM11yYGQslMOkp', 'name': 'DJ Storm', 'type': 'artist', 'uri': 'spotify:artist:9Cv3GYUzNM11yYGQslMOkp'}
]

I tried this approach but it’s not working:

print(music_data[spotify:artist])

What I want to get is the ID part from each URI, so the output should be:
[7XB93KLm2VqzHRPiVczEU2] [2M84eBRlVxd4v4YnccZlvs] [9Cv3GYUzNM11yYGQslMOkp]

How can I loop through this data structure and extract just those specific values from the URI field?

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.