This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Hi all,
The code snippet I need help with uses the Spotify API to find artists that use certain genres as tags. The variable "results" is a dictionary of dictionaries of three artists who use said genre (I don't know why it's not returned as a json, but I'm not mad). In this dictionary there is a lot of information I don't need, so the function picks out the information I need and makes new, smaller dictionaries that it then appends to a list to be used later on in the program. So far, so good. However, I don't want the program to crash if certain information doesn't exist for an artist down the line. Say if they don't have an image, or whatever.
So, I was wondering if there was a way to have it default to a certain value if a key doesn't exist in the results dictionary. If a key does exist and the value is None, that's fine. The suggested thing is to use defaultdict, which honestly makes my brain fall flat. Would it be 'pythonic' to first make a dictionary on every iteration of the loop with all the values set to None, and then override them if they do exist? I feel like I could make that work, but it feels inelegant.
Here is the function in question:
def find_artists(targets: list = None) -> list:
"""
:param targets: Takes a list of genres to be searched for
:return: Returns a list of dictionaries that contain
the genre, artist_name, follower_count, artist_image, and the url
"""
artists = []
for genre in targets:
results = spotify.search(q=f'genre:{genre}', type='artist', limit=3)
for entry in results["artists"]["items"]:
temp_dict = {
'genre': genre,
'artist_name': entry['name'],
'follower_count': entry['followers']['total'],
'artist_image': entry['images'][0]['url'],
'url': entry['external_urls']['spotify']
}
artists.append(temp_dict)
return artists
I took a long break from coding, and am just now getting back into it, so I'm rusty as heck. Excuse any obvious errors, but please point them out! Also, let me know if you don't think this would be an issue, I'm not very versed in APIs.
Thanks in advance for your time.
EDIT: Typos and fixed the code block
Subreddit
Post Details
- Posted
- 11 months ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learnpython...