Reputation: 1032
So I haven't exactly used Python in a while and I'm rusty - I'm working on a personal project and the API I'm using returns a list of dictionaries that represent a song's data. What I'm trying to do is essentially trim down the returned list of songs to ONLY those with a rating of 5 (and to delete all others from the list). I have some code below that doesn't seem to be working. It doesn't seem to actually remove anything, and prints out the entire list of songs (which in my case gets pretty large, as it is around 11,000 songs or so).
As a bit of help, I'll also post an example of what the API returns (for one song):
{
'comment':'',
'rating':'0',
'albumArtRef':[
{
'url': 'http://lh6.ggpht.com/...'
}
],
'artistId':[
'Aod62yyj3u3xsjtooghh2glwsdi'
],
'composer':'',
'year':2011,
'creationTimestamp':'1330879409467830',
'id':'5924d75a-931c-30ed-8790-f7fce8943c85',
'album':'Heritage ',
'totalDiscCount':0,
'title':'Haxprocess',
'recentTimestamp':'1372040508935000',
'albumArtist':'',
'trackNumber':6,
'discNumber':0,
'deleted':False,
'storeId':'Txsffypukmmeg3iwl3w5a5s3vzy',
'nid':'Txsffypukmmeg3iwl3w5a5s3vzy',
'totalTrackCount':10,
'estimatedSize':'17229205',
'albumId':'Bdkf6ywxmrhflvtasnayxlkgpcm',
'beatsPerMinute':0,
'genre':'Progressive Metal',
'playCount':7,
'artistArtRef':[
{
'url': 'http://lh3.ggpht.com/...'
}
],
'kind':'sj#track',
'artist':'Opeth',
'lastModifiedTimestamp':'1330881158830924',
'clientId':'+eGFGTbiyMktbPuvB5MfsA',
'durationMillis':'418000'
}
And my code is as follows:
library = api.get_all_songs()
print("There are",len(library),"items in your music library")
for track in library:
if track['rating'] != 5:
library.remove(track)
print("You have",len(library),"favorite tracks!")
return library
I added in the "favorite songs" amount (as well as the number of songs in the library) to test and see if my loop and if statement would remove anything, and it doesn't (as the numbers are the same before and after the loop) - I figure it has something to do with that, as the code works fine otherwise, it just doesn't prune the list.
If any extra code is needed, I'd be more than happy to provide it.
Upvotes: 0
Views: 78
Reputation: 15300
Try a list comprehension to filter your list of dictionaries:
library = ...
good_songs = [ x for x in library if x['rating'] == '5' ]
Upvotes: 3
Reputation: 397
The API is treating the rating as a string.
You are treating the rating as an integer. That's why no track is ever deleted.
Upvotes: 1