python - More Efficient Way of Reading Large List of dicts -
for project use mutagen library read id3 tags 5000+ mp3 files. after reading them construct following objects using them.
class track: def __init__(self, artist, title, album=none): self.artist = artist self.title = title self.album = none def __str__(self): return "track: %s : %s" % (self.artist,self.title, ) def set_album(self,album): self.album = album class album: def __init__(self, artist, title, year='', genre='', tracks=none): self.artist = artist self.year = year self.genre = genre self.title = title self.tracks = [] def __str__(self): return "album: %s : %s [%d]" % (self.artist,self.title,len(self.tracks)) def add_track(self,track): self.tracks.append(track)
the problem files missing required tags(title missing,artist missing, or both), causing keyvalueerror
#'talb' (album title), 'tit2' (track title), 'tpe1' (artist), 'tdrc' (year), , 'tcon' (genre) root, dirs, files in os.walk(dir): filename in files: if filename.lower().endswith(e): fullname = os.path.join(root, filename) try: audio = mutagen.file(fullname) track = track(audio['tpe1'],audio['tit2']) album = album(audio['tpe1'], audio['talb'], audio['tdrc'], audio['tcon']) excpet exception e: print "error on %s. %s " % (filename,type(e).__name__)
this loads files have tags, not enough. solved problem using ifs, works fine , fast enough. wonder if there better way of handling this.
if default value can empty string instead of none
use defaultdict.
>>> >>> collections import defaultdict >>> d = defaultdict(str) >>> d['a'] = 'data' >>> d['b'] = 1 >>> d defaultdict(<type 'str'>, {'a': 'data', 'b': 1}) >>> = d['a'] >>> b = d['b'] >>> c = d['c'] >>> a, b, c ('data', 1, '') >>> d defaultdict(<type 'str'>, {'a': 'data', 'c': '', 'b': 1}) >>>
Comments
Post a Comment