I'm trying to do the following thing: parse all the files in my music folder and if they are among my favorites, copy them to a separate folder.
In order to achieve this, I'm parsing an xml with my loved tracks and use the info to create a custom dictionary structured like this
lovedSongs[artist][title] = 1
When I'm parsing the files from my folder, I read the song title and artist from the id3 tags and, in theory, I try to see if lovedSongs[tagArtist][tagTitle]
is 1
for filename in filelist:
if filename[-4:] == ".mp3":
try:
id3r = id3reader.Reader(filename)
except UnicodeDecodeError:
artist = "None"
title = "None"
except IOError:
artist = "None"
title = "None"
else:
artist = ensureutf8andstring(id3r.getValue('performer'))
title = ensureutf8andstring(id3r.getValue('title'))
if artist != "None" or title != "None":
if lovedSongs[artist][title] == 1:
print artist + ' - ' + title
When I try to run the .py file, I get a dictionary Key Error. I found a potential answere here: How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError? and applied it like below, but I still got the Key Error
class SongDict(dict):
def __init__(self, default=None):
self.default = default
def __getitem__(self, key):
if not self.has_key(key):
self[key] = self.default()
return dict.__getitem__(self, key)
def __missing__(self, key):
return 0
What would be the best solution? Use try/except perhaps instead of the simple if?
P.S. I think I should mention that I'm a newbie to python, with only a couple of hours of 'experience' and this is my way of trying to learn the language.