Graded = 8/8


In [1]:
import requests
response = requests.get('https://api.spotify.com/v1/search?query=Lil&type=artist&market=US&limit=50')
data = response.json()

In [2]:
# 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.
# 2) What genres are most represented in the search results? Edit your previous printout to also display a list of their genres in the format "GENRE_1, GENRE_2, GENRE_3". If there are no genres, print "No genres listed".

artists = data['artists']['items']
genre_list = []
count = 1
for artist in artists:
    genres = 'no genres listed'
    if len(artist['genres']) > 0:
        genres = str.join(", ", artist['genres'])
        genre_list.extend(artist['genres'])
    print("#" + str(count), str(artist['name']) + ":", str(artist['popularity']) + ",", genres)
    count += 1

print("\n")
for genre in set(genre_list):
    theCount = genre_list.count(genre)
    if theCount == 1:
        print("The genre", "“" + genre + "”", "appears once.")
    else:
        print("The genre", "“" + genre + "”", "appears", theCount, "times.")


#1 Lil Wayne: 86, dirty south rap, pop rap, southern hip hop, trap music
#2 Lil Yachty: 74, no genres listed
#3 Lil Uzi Vert: 74, no genres listed
#4 Lil Dicky: 69, no genres listed
#5 Boosie Badazz: 67, no genres listed
#6 Lil Jon: 72, crunk, dirty south rap, southern hip hop
#7 King Lil G: 61, no genres listed
#8 Lil Durk: 60, no genres listed
#9 Lil Jon & The East Side Boyz: 60, no genres listed
#10 Lil Bibby: 54, no genres listed
#11 G Herbo: 53, no genres listed
#12 Lil Rob: 50, chicano rap, latin hip hop
#13 Lil Reese: 50, no genres listed
#14 Lil Scrappy: 50, crunk, dirty south rap, southern hip hop, trap music
#15 Bow Wow: 57, hip pop, pop rap
#16 Lil Keke: 48, no genres listed
#17 Lil Wyte: 50, juggalo
#18 Lil Blood: 46, no genres listed
#19 Lil Snupe: 45, no genres listed
#20 Lil Mama: 45, hip pop
#21 Lil Boom: 46, no genres listed
#22 Lil B: 44, no genres listed
#23 Lil' Kim: 62, hip pop
#24 Lil Cuete: 40, chicano rap
#25 Lil Phat: 40, no genres listed
#26 Lil Debbie: 43, no genres listed
#27 Lil Twist: 40, jerk
#28 Lil Trill: 37, deep trap
#29 Lil Goofy: 36, no genres listed
#30 Lil Lonnie: 37, no genres listed
#31 Lil AJ: 37, no genres listed
#32 Lil Haiti: 38, no genres listed
#33 Lil Cray: 36, no genres listed
#34 Lil Twon: 36, no genres listed
#35 Mr. Lil One: 36, chicano rap
#36 Lil Mouse: 35, no genres listed
#37 Lil Silva: 43, no genres listed
#38 Lil Yase: 34, no genres listed
#39 Lil Flash: 38, no genres listed
#40 Lil Suzy: 34, freestyle
#41 Lil Eddie: 41, no genres listed
#42 Lil Rue: 34, no genres listed
#43 Lil Kesh: 39, no genres listed
#44 Lil Wayne, DJ Drama: 35, no genres listed
#45 Lil C: 33, no genres listed
#46 Lil Rick: 39, soca
#47 Lil E: 35, no genres listed
#48 Lil June: 32, no genres listed
#49 Lil Fate: 34, no genres listed
#50 Lil' Flip: 50, crunk, dirty south rap


The genre “southern hip hop” appears 3 times.
The genre “latin hip hop” appears once.
The genre “hip pop” appears 3 times.
The genre “dirty south rap” appears 4 times.
The genre “jerk” appears once.
The genre “freestyle” appears once.
The genre “pop rap” appears 2 times.
The genre “trap music” appears 2 times.
The genre “crunk” appears 3 times.
The genre “juggalo” appears once.
The genre “deep trap” appears once.
The genre “soca” appears once.
The genre “chicano rap” appears 3 times.

In [3]:
# 3) Use a for loop to determine who BESIDES Lil Wayne has the highest popularity rating.
# Is it the same artist who has the largest number of followers?

# we scan the 'popularity' and 'followers' values
max_popularity = 0
most_popular_index = 0
max_followers = 0
most_followers_index = 0

max_range = len(artists)-1

for index in range(1, max_range): # we start at 1 to skip Lil Wayne
    if artists[index]['popularity'] > max_popularity:
        max_popularity = artists[index]['popularity']
        most_popular_index = index
    if artists[index]['followers']['total'] > max_followers:
        max_followers = artists[index]['followers']['total']
        most_followers_index = index

print("The most popular besides Lil Wayne is", str(artists[most_popular_index]['name']) + ".")
print("She has", artists[most_popular_index]['followers']['total'], "followers.")
print("With", artists[most_followers_index]['followers']['total'], "followers,", artists[most_followers_index]['name'], 'has the largest number of followers.')

# 4) Print a list of Lil's that are more popular than Lil' Kim.

# Lik' Kim has a popularity of 62.

more_popular = []
for artist in artists:
    if artist['popularity'] > 62:
        more_popular.append(artist['name'])
print("Following artists are more popular than Lil' Kim:", str.join(', ', more_popular) + ".")


The most popular besides Lil Wayne is Lil Yachty.
She has 43887 followers.
With 257190 followers, Lil Jon has the largest number of followers.
Following artists are more popular than Lil' Kim: Lil Wayne, Lil Yachty, Lil Uzi Vert, Lil Dicky, Boosie Badazz, Lil Jon.

In [4]:
# 5) Pick two of your favorite Lils to fight it out, and use their IDs to print out their top tracks.
# Tip: You're going to be making two separate requests, be sure you DO NOT save them into the same variable.

lil_1 = requests.get('https://api.spotify.com/v1/artists/4O15NlyKLIASxsJ0PrXPfz/top-tracks?country=US')
lil_1_data = lil_1.json()

lil_1_topTracks = []
for topTrack in lil_1_data['tracks']:
    lil_1_topTracks.append(topTrack['name'])

print("Lil Uzi Vert's top tracks:", str.join(', ', lil_1_topTracks))

lil_2 = requests.get('https://api.spotify.com/v1/artists/6icQOAFXDZKsumw3YXyusw/top-tracks?country=US')
lil_2_data = lil_2.json()

lil_2_topTracks = []
for topTrack in lil_2_data['tracks']:
    lil_2_topTracks.append(topTrack['name'])

print("Lil Boat's top tracks:", str.join(', ', lil_2_topTracks))


Lil Uzi Vert's top tracks: Money Longer, You Was Right, Top, Ps & Qs, 7am, Canadian Goose, Hi Roller, All My Chains, Baby Are You Home, Grab the Wheel
Lil Boat's top tracks: One Night (Extended), Minnesota (Remix) [feat. Quavo, Skippa da Flippa & Young Thug], Wanna Be Us (feat. Burberry Perry), Intro (Just Keep Swimming), Up Next 2 (feat. Big Brutha Chubba & Byou), Good Day (feat. Skippa da Flippa), Not My Bro, Fucked Over, Out Late, Interlude

In [5]:
# 6) Will the world explode if a musicians swears?
# Get an average popularity for their explicit songs vs. their non-explicit songs.

tracks_count_Vert = {'exp': 0, 'non-exp': 0}
tracks_popularity_Vert = {'exp': 0, 'non-exp': 0}
tracks_ms_Vert = {'exp': 0, 'non-exp': 0}

for topTrack in lil_1_data['tracks']:
    if topTrack['explicit'] == True:
        tracks_count_Vert['exp'] += 1
        tracks_popularity_Vert['exp'] += topTrack['popularity'] # currently: a sum
        tracks_ms_Vert['exp'] += topTrack['duration_ms']
    else:
        tracks_count_Vert['non-exp'] += 1
        tracks_popularity_Vert['non-exp'] += topTrack['popularity'] # currently: a sum
        tracks_ms_Vert['non-exp'] += topTrack['duration_ms']

if tracks_count_Vert['exp'] > 0: # prevent division by 0
    tracks_popularity_Vert['exp'] /= tracks_count_Vert['exp']

if tracks_count_Vert['non-exp'] > 0:
    tracks_popularity_Vert['non-exp'] /= tracks_count_Vert['non-exp']

print("The average popularity of Lil Uzi Vert's explicit tracks is", tracks_popularity_Vert['exp'], "and the average popularity of her non-explicit tracks is", str(tracks_popularity_Vert['non-exp']) + '.')

# How many minutes of explicit songs do they have? Non-explicit?

print("Lil Uzi Vert has", "%.2f" % (tracks_ms_Vert['exp']/60000), "minutes of explicit songs and", "%.2f" % (tracks_ms_Vert['non-exp']/60000), "of non-explicit songs.")


tracks_count_Boat = {'exp': 0, 'non-exp': 0}
tracks_popularity_Boat = {'exp': 0, 'non-exp': 0}
tracks_ms_Boat = {'exp': 0, 'non-exp': 0}

for topTrack in lil_2_data['tracks']:
    if topTrack['explicit'] == True:
        tracks_count_Boat['exp'] += 1
        tracks_popularity_Boat['exp'] += topTrack['popularity'] # currently: a sum
        tracks_ms_Boat['exp'] += topTrack['duration_ms']
    else:
        tracks_count_Boat['non-exp'] += 1
        tracks_popularity_Boat['non-exp'] += topTrack['popularity'] # currently: a sum
        tracks_ms_Boat['non-exp'] += topTrack['duration_ms']

if tracks_count_Boat['exp'] > 0: # prevent division by 0
    tracks_popularity_Boat['exp'] /= tracks_count_Boat['exp']

if tracks_count_Boat['non-exp'] > 0:
    tracks_popularity_Boat['non-exp'] /= tracks_count_Boat['non-exp']

print("The average popularity of Lil Boat's explicit tracks is", tracks_popularity_Boat['exp'], "and the average popularity of her non-explicit tracks is", str(tracks_popularity_Boat['non-exp']) + '.')

# How many minutes of explicit songs do they have? Non-explicit?

print("Lil Boat has", "%.2f" % (tracks_ms_Boat['exp']/60000), "minutes of explicit songs and", "%.2f" % (tracks_ms_Boat['non-exp']/60000), "of non-explicit songs.")


The average popularity of Lil Uzi Vert's explicit tracks is 67.0 and the average popularity of her non-explicit tracks is 0.
Lil Uzi Vert has 37.82 minutes of explicit songs and 0.00 of non-explicit songs.
The average popularity of Lil Boat's explicit tracks is 60.4 and the average popularity of her non-explicit tracks is 0.
Lil Boat has 31.16 minutes of explicit songs and 0.00 of non-explicit songs.

In [6]:
# 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?

# to be fair, we target the US market again
responseBig = requests.get('https://api.spotify.com/v1/search?query=Biggie&type=artist&market=US&limit=50')
dataBig = responseBig.json()

print("There is", data['artists']['total'], "results for “Lil” and", dataBig['artists']['total'], "for “Biggie”.")


print("It would take about", (data['artists']['total']*4500)/3600, "hours to get the results for the “Lil” and", (dataBig['artists']['total']*4500)/3600, "hours for the “Biggie”.")


There is 4526 results for “Lil” and 50 for “Biggie”.
It would take about 5657.5 hours to get the results for the “Lil” and 62.5 hours for the “Biggie”.

In [7]:
# 8) Out of the top 50 "Lil"s and the top 50 "Biggie"s, who is more popular on average?

artistsBig = dataBig['artists']['items']

sumPopLil = 0
for artistLil in artists:
    sumPopLil += artistLil['popularity']

sumPopBig = 0
for artistBig in artistsBig:
    sumPopBig += artistBig['popularity']

print("The top 50 “Lil” is more popular, with an average popularity of", sumPopLil / len(artists), "vs.", str(sumPopBig / len(artistBig)) + " for the 49 “Biggie”.")


The top 50 “Lil” is more popular, with an average popularity of 46.7 vs. 19.5 for the 49 “Biggie”.

In [ ]:
# LIL' GRAPHICS
# # Just a simple bar graph of their various popularities sounds good to me.

# NB: Maybe you'll need to run this code twice in order for d3.js to be fully loaded

from IPython.display import display, HTML

artistNames = []
artistPop = []
for artistLil in artists:
    artistNames.append(artistLil['name'])
    artistPop.append(artistLil['popularity'])
    
html = []
html.append('<style>.chart div {  font: 10px sans-serif;  background-color: steelblue;  text-align: right;  padding: 3px;  margin: 1px;  color: white;}</style><div class="chart"></div><script src="http://d3js.org/d3.v3.min.js"></script>')
html.append('<script>')
html.append('var lil_data = ' + str(artistPop) + ';')
html.append('var lil_names = ' + str(artistNames) + ';')
html.append('var x = d3.scale.linear()    .domain([0, d3.max(lil_data)])    .range([0, 420]);d3.select(".chart")  .selectAll("div")    .data(lil_data)  .enter().append("div")    .style("width", function(d) { return x(d) + "px"; })    .text(function(d, i) { return lil_names[i] + ": " + d; });</script></body></html>')

d3Graph = str.join('', html)

# Uncomment next line to generate the graph dynamically:
#display(HTML(d3Graph))

Screen capture of the graph for the static page:


In [ ]:
# SEARCH ENGINE
# 
# Make a non-IPython Notebook that automates browsing for top tracks
# Prompts for an artist

requested_artist = input("Search for…\n")
search_result = requests.get('https://api.spotify.com/v1/search?query=' + requested_artist + '&type=artist')
search_result_data = search_result.json()
artists_result = search_result_data['artists']['items']
length_result = len(artists_result)
print(length_result, "results!")
for i in range(1, length_result+1):
    print('#' + str(i), artists_result[i-1]['name'])

# you put it in, displays the results, asks which one you want (numbered)
wanted_artist = input("\nWhich one do you want?\n")

# Never trust users
try:
    wanted_artist_int = int(wanted_artist)-1
except ValueError:
    print("Next time, please choose an integer. I picked up number 1 for you.")
    wanted_artist_int = 0

if wanted_artist_int < 0 or wanted_artist_int > length_result-1:
    print("This number is out of range.")
else:
    wanted_artist_id = artists_result[wanted_artist_int]['id']
    print("\nRetrieving information about", artists_result[wanted_artist_int]['name'] + "...\n")
    
# Display their top tracks
    wanted_tracks = requests.get('https://api.spotify.com/v1/artists/' + wanted_artist_id + '/top-tracks?country=US')
    wanted_tracks_data = wanted_tracks.json()
    theTrackResults = []
    for topTrack in wanted_tracks_data['tracks']:
        theTrackResults.append(topTrack['name'])
    if len(theTrackResults) > 1:
        print("Top tracks:", str.join(', ', theTrackResults))
    else:
        print("Top track:", str.join(', ', theTrackResults))

    # Their MOST popular album and their least popular album.
    
    # 1) We retreive the ids of the albums
    wanted_albums = requests.get('https://api.spotify.com/v1/artists/' + wanted_artist_id + '/albums')
    wanted_albums_data = wanted_albums.json()
    album_id_list = []
    for album in wanted_albums_data['items']:
        album_id_list.append(album['id'])

    # 2) We load these albums to get their popularity
    search_result = requests.get('https://api.spotify.com/v1/albums/?ids=' + str.join(',',album_id_list))
    search_result_data = search_result.json()
    albums = search_result_data['albums']

    album_hits = len(albums)
    if(album_hits) < 1:
        print("No album could be retrieved.")
    elif(album_hits) == 1:
        print("This artist has only one album on Spotify: “" + str(albums[0]['name']) + "”.")
    else:    
        album_popularity = []
        album_name = []
        for album in albums:
            album_popularity.append(album['popularity'])
            album_name.append(album['name'])
        
        print("\n" + str(album_hits), "albums found.")
        most_popular_album_index = album_popularity.index(max(album_popularity))
        least_popular_album_index = album_popularity.index(min(album_popularity))
        
        
        print("The album “" + album_name[most_popular_album_index] + "” is the most popular, with a popularity score of", str(album_popularity[most_popular_album_index]) + ".")
        print("The album “" + album_name[least_popular_album_index] + "” is the least popular, with a popularity score of", str(album_popularity[least_popular_album_index]) + ".")