Nov-26-2019, 04:47 AM
I have a file that contains songs recently played by a radio station, the artist, and time played in this format: "November 4, 2019 8:02 PM","Wagon Wheel","Darius Rucker". I am trying to store the content of this file in string variable playlist_csv, use splitlines() to store records in variable lines, and then iterate through the lines to store data in a dictionary. The key should be a datetime object of the timestamp, and the value should be a tuple of song and artist: {datetime_key: (song, artist)}
This is what I have for code so far:
I appreciate any help!
This is what I have for code so far:
# read the file and store content in string variable playlist_csv with open('playlist.txt', 'r') as csv_file: playlist_csv = csv_file.read().replace('\n', '') # use splitlines() method to store records in variable lines (it is list) split_playlist = playlist_csv.splitlines() # iterate through lines to store data in playlist_dict dictionary playlist_dict = {} for l in csv.reader(split_playlist, quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True): dt=datetime.strptime(l[0], '%B %d, %Y %I:%M %p') playlist_dict[l[dt]].append(dt) print(playlist_dict)However, I keep running into errors when trying to store this data in a dictionary (specifically "'datetime.datetime' object is not subscriptable" and "list indices must be integers or slices" when modifying the code). Desired output looks like: {datetime.datetime(2019, 11, 4, 20, 2): ('Wagon Wheel', 'Darius Rucker'),...}
I appreciate any help!