In [1]:
#1) With "Lil Wayne" and "Lil Kim" there are a lot of "Lil" musicians.
#Do a search and print a list of 50 that are playable in the USA
#(or the country of your choice), along with their popularity score.
In [2]:
import requests
In [3]:
response = requests.get('https://api.spotify.com/v1/search?query=lil&type=artist&market=US&limit=50')
& for multiple parameters
In [4]:
data = response.json()
In [5]:
data.keys()
Out[5]:
In [6]:
artist_data = data['artists']
In [7]:
artist_data.keys()
Out[7]:
In [8]:
lil_names = artist_data['items']
#lil_names = list of dictionaries = list of artist name, popularity, type, genres etc
In [9]:
for names in lil_names:
if not names['genres']:
print(names['name'], names['popularity'], "there are no genres listed")
else:
print(names['name'], names['popularity'], names["genres"])
#Join all the lists of genres in the dictionary and then count the number of elements in it
ANSWER: for artist in artists: print(artist['name'], artist['popularity']) if len(artist['genres']) > 0: genres = ", ".join(artist['genres']) print("Genre list: ", genres else: print("No genres listed")
OR
if len(artist['name']) == 0:
OR
if not len(artist['genres']) == 0:
In [14]:
#ANSWER:
all_genres = []
for artist in artists:
print("All genres we've heard of:", all_genres)
#The conditional: None
print("Current artist has:", artist['genres'])
all_genres = all_genres + artist['genres']
#genre_list = ", ".join(artist['genres'])
#print(artist['name'], ":", genre_list)
all_genre.count('dirty soup rap')
all_genre.count('crunk')
#This is bad because dirty south rap shows up four times. We need a unique list of genres
for genre in all_genres:
genre_count = all_genres.count(genre)
print(genre, "shows up", genre_count, "times")
#To remove duplicates. You need to turn a list into a set.
unique_genres = set(list_with_duplicates)
for genre in unique_genres:
genre_count = all_genres.count(genre)
print(genre, "shows up", genre_count, "times")
In [11]:
#There is a library that comes with Python called Collections
#Inside of it is a magic thing called Counter.
import collections # will import the whole collections
#you can also type
from collections import Counter
#all_genres is a list of strings of genrs with duplicates
#counter will count all te genres for us
counts = collections.Counter(all_genres)
counts.most_common(4) #will give you the four most common genres
In [ ]:
#HOW TO AUTOMATE GETTING ALL THE RESULTS
response = requests.get("https://api.spotify.com/v1/search?query=lil&type=artist&market=US&limit=10")
small_data = response.json()
In [ ]:
small_data['artists']
print(len(small_data['artists']['items'])) #We only get 10 artists
print(data['artists']['total'])
import math
page_count = math.ceil(4502/50)
#math.ceil rounds up
#math.ceil(page_count)
page_count
In [ ]:
#First page artists 1-50:
#https://api.spotify.com/v1/search?query=lil&type=artist&market=US&limit=50
#Second page artists 51-100:
#https://api.spotify.com/v1/search?query=lil&type=artist&market=US&limit=50&offset=50
#Third page artists 101-150:
#https://api.spotify.com/v1/search?query=lil&type=artist&market=US&limit=50&offset=100
#Fourth page artists 151-200:
#https://api.spotify.com/v1/search?query=lil&type=artist&market=US&limit=50&offset=150
for page in [0, 1, 2, 3, 4]:
offset = (page) * 50 #because page 2 is 50 and 2-1 = 1 x 50 = 50
print("We are on page", page, "with an offset of", offset)
In [ ]:
for page in range(91):
#Get a page
offset = page * 50
print("We are on page", page, "with an offset of", offset)
#Make the request with a changed offset ?offset [offset]
#data = response.json()
#add all our new artists to our list of existing artists
#all_artists = all_artists + data['artists]['items]
print("Successfully retrieved", len(all_artists), "artists")
In [ ]:
for popularity in lil_names:
print(popularity['name'], popularity['popularity'], popularity['followers'])
print("Lil Yachty, Lil Uzi Vert, Lil Jon have the highest popularity ratings besides Lil Wayne, and they do not have the largest number of followers.")
ANSWER:
#jonathansoma.com/site/lede/foundations/python-patterns/looping-problems/
second_most_popular_name = "" second_most_popular_score = 0 for artist in artists: print("Looking at", artist['name]', "who has a popularity score of", artist['popularity'])
#THE CONDITIONAL aka what you are testing
print("Comparing", artist['popularity'], "to", most_popular_score)
if artist['popularity'] > most_popular_score and artist['name'] != 'Lil Wayne':
OR
if artist['popularity'] > most_popular_score:
if artist['name'] == "Lil Wayne":
print("Nice try, Lil Wayne, we don't care")
else:
print("Not Lil Wayne, updating our notebook")
#The change, aka what you are keeping track of
most_popular_name = artist['name']
most_popular_score = artist['popularity']
print(most_popular_name, most_popular_score)
target score = 72
second_best_artist = []
for artist in artists: print("Looking at", artist['name'], "who has a popularity of", )
#2: Conditional. When we want to add someone to our list
if artist['popularity'] == 72:
print("!!! The artist's popularity is 72")
#The Change
#Add that artist to our list
#.append(newthing) is how we do that in Python
second_best_artists.append(artist['name'])
print("Our second best artists are:")
for artist in second_best_artist:
print(artist)
Print a list of Lil's that are more popular than Lil' Kim.
In [ ]:
for kim in lil_names:
print(kim['name'], kim['id'])
In [ ]:
response = requests.get("https://api.spotify.com/v1/artists/5tth2a3v0sWwV1C7bApBdX/")
kim_data = response.json()
In [ ]:
#print(kim_data)
kim_followers = kim_data['followers']
total_kim_followers = kim_followers['total']
#print(total_kim_followers)
for artists in lil_names:
if artists["followers"]["total"] > total_kim_followers:
print(artists['name'], artists['popularity'])
In [ ]:
ANSWER:
for artist in artists:
#print("Looking at", artist['name'])
if artist['name'] == "Lil' Kim":
print("Found Lil Kim")
print(artist['popularity'])
else:
pass
#print("Not Lil Kim")
lil_kim_popularity = 62
for artist in artists:
if artist['popularity'] > lil_kim_popularity:
print(artist['name'], "is more popular with a score of", artist['popularity'])
more_popular_than_lil_kim.append(artist['name'])
else:
print(artist['name'], "is less popular with a score of", artist['popularity'])
print("#### More popular than Lil Kim ####"):
print(artist_name)
more_popular_string = ", ".join(more_popular_than_lil_kim)
print("Artists mroe popular than Lil Kim are:", more_popular_string)
5) Pick two of your favorite Lils to fight it out, and use their IDs to print out their top tracks.
In [ ]:
#Let's pick Lil Wayne and Lil Mama because I don't know who most of these people are
wayne_id = "55Aa2cqylxrFIXC767Z865"
response = requests.get("https://api.spotify.com/v1/artists/" + wayne_id + "/top-tracks?country=US")
wayne_data = response.json()
top_wayne_tracks = wayne_data['tracks']
for track in top_wayne_tracks:
print(track["name"])
In [ ]:
mama_id = "5qK5bOC6wLtuLhG5KvU17c"
response = requests.get("https://api.spotify.com/v1/artists/" + mama_id + "/top-tracks?country=US")
mama_data = response.json()
top_mama_tracks = mama_data['tracks']
for track in top_mama_tracks:
print(track["name"])
Will the world explode if a musician swears? Get an average popularity for their explicit songs vs. their non-explicit songs. How many minutes of explicit songs do they have? Non-explicit?
In [ ]:
wayne_explicit_count = 0
wayne_exp_popularity_count = 0
wayne_ok_count = 0
wayne_ok_popularity_count = 0
wayne_explicit_len = 0
wayne_ok_len = 0
for track in top_wayne_tracks:
print(track['name'], track['explicit'], track['popularity'], track["duration_ms"])
if True:
wayne_explicit_count = wayne_explicit_count + 1
wayne_exp_popularity_count = wayne_exp_popularity_count + int(track['popularity'])
wayne_avg_pop = wayne_exp_popularity_count / wayne_explicit_count
wayne_explicit_len = wayne_explicit_len + int(track["duration_ms"])
if not track['explicit']:
wayne_ok_count = wayne_ok_count + 1
wayne_ok_popularity_count = wayne_ok_popularity_count + track['popularity']
wayne_ok_avg_pop = wayne_ok_popularity_count / wayne_ok_count
wayne_ok_len = wayne_ok_len + track["duration_ms"]
if wayne_explicit_count > 0:
print("The average popularity for Lil Wayne's explicit songs is", wayne_avg_pop)
#1 minute is 60000 milliseconds, who knew?
wayne_explicit_mins = int(wayne_explicit_len) / 60000
print("Lil Wayne has", wayne_explicit_mins, "minutes of explicit songs")
if wayne_ok_count > 0:
print("The average popularity for Lil Wayne's non-explicit songs is", wayne_ok_avg_pop)
wayne_ok_mins = int(wayne_ok_len) / 60000
print("Lil Wayne has", wayne_ok_mins, "minutes of explicit songs")
for track in top_mama_tracks: print(track['name'], track['explicit']) if True: print(track['name'], "is explicit and has a popularity of", track['popularity']) if not track['explicit']: print(track['name'], "is not explicit and has a popularity of", track['popularity'])
In [ ]:
mama_exp_count = 0
mama_exp_pop_count = 0
mama_ok_count = 0
mama_ok_pop_count = 0
mama_exp_len = 0
mama_ok_len = 0
for track in top_mama_tracks:
print(track['name'], track['explicit'], track['popularity'], track["duration_ms"])
if True:
mama_exp_count = mama_exp_count + 1
mama_exp_pop_count = mama_exp_pop_count + int(track['popularity'])
mama_avg_pop = int(mama_exp_pop_count) / int(mama_exp_count)
mama_exp_len = mama_exp_len + int(track["duration_ms"])
if not track['explicit']:
mama_ok_count = mama_ok_count + 1
mama_ok_pop_count = mama_ok_pop_count + int(track['popularity'])
mama_ok_avg_pop = int(mama_ok_pop_count) / int(mama_ok_count)
mama_ok_len = mama_ok_len + int(track["duration_ms"])
if mama_exp_count > 0:
#1 minute is 60000 milliseconds, who knew?
print("The average popularity for Lil Mama's xplicit songs is", mama_avg_pop)
mama_exp_mins = int(mama_exp_len) / 60000
print("Lil Mama has", mama_exp_mins, "minutes of explicit songs")
if mama_ok_count > 0:
print("The average popularity for Lil Mama's non-explicit songs is", mama_ok_avg_pop)
mama_ok_mins = int(mama_ok_len) / 60000
print("Lil Mama has", mama_ok_mins, "minutes of non-explicit songs")
7) Since we're talking about Lils, what about Biggies? How many total "Biggie" artists are there? How many total "Lil"s? If you made 1 request every 5 seconds, how long would it take to download information on all the Lils vs the Biggies?
In [ ]:
#We need to bypass the limit. And find out
In [ ]:
response = requests.get('https://api.spotify.com/v1/search?query=biggie&type=artist')
In [ ]:
biggie_data = response.json()
In [ ]:
biggie_artists = biggie_data['artists']
biggie_names = biggie_artists['items']
biggie_count= 0
for name in biggie_names:
print(name['name'])
biggie_count = biggie_count + 1
print("There are a total number of", biggie_count, "biggie artists")
In [ ]:
response = requests.get('https://api.spotify.com/v1/search?query=lil&type=artist')
In [ ]:
lil_data = response.json()
In [ ]:
lil_x_artists = lil_data['artists']
lil_x_names = lil_x_artists['items']
lil_x_count= 0
for name in lil_x_names:
print(name['name'])
lil_x_count = biggie_count + 1
print("There are a total number of", lil_x_count, "lil artists")
8) Out of the top 50 "Lil"s and the top 50 "Biggie"s, who is more popular on average?
In [ ]:
response = requests.get('https://api.spotify.com/v1/search?query=biggie&type=artist&limit=50')
In [ ]:
b_data = response.json()
In [ ]:
b_artists = b_data['artists']
b_names = b_artists['items']
b_pop_count = 0
b_number = 0
for names in b_names:
print(names['name'], names['popularity'])
b_number = b_number + 1
b_pop_count = b_pop_count + int(names['popularity'])
avg_b_pop = b_pop_count / int(b_number)
print("The Biggies' average popularity is", avg_b_pop)
In [ ]:
lil_pop_count = 0
lil_number = 0
for names in lil_names:
print(names['name'], names['popularity'])
lil_number = lil_number + 1
lil_pop_count = lil_pop_count + int(names['popularity'])
avg_lil_pop = lil_pop_count / int(lil_number)
print("The Lils average popularity is", avg_lil_pop)
In [ ]:
print("The Lils are far more popular")
In [ ]: