1

So I've got this little script that adds songs to an Rdio playlist. It mostly works just fine. First it reads a CSV and creates a list of dictionaries, with each dictionary containing attributes for the track. Here's the code that does that:

csv_tracks = []
f = open('./testing_tracks.csv', 'rb')
reader = csv.reader(f)
for row in reader:
    csv_tracks.append({'artist':row[1], 'title':row[0], 'status':row[2]})
f.close

The 'status' value is a string of either 0 or 1, just to signal whether the track has already been added to the playlist (so I don't keep re-adding the same track over and over).

The problem appears later in the script, where I run a loop to search for each track on Rdio, and add it to a playlist if found. Here's the code:

for track in csv_tracks:
    if track['status'] == '0':
        if find_track(track) != None:
            key = find_track(track)
            add_to_playlist(key)
            track['status'] = '1'
            print 'Adding %s by %s to the playlist' % (track['title'],track['artist'])

I get a TypeError. Here's the message:

Traceback (most recent call last):
  File "testing.py", line 76, in <module>
    if track['status'] == '0':
TypeError: list indices must be integers, not str

The truly odd thing is that the script seems to work mostly fine. For tracks with status == '0', it searches for them and adds them to the playlist and then logs a message as per above ('Adding...to the playlist'). The only thing that doesn't work is track['status'] is not changed to '1' when a track is added. And I get the error.

I don't really understand why Python seems to think that my dictionary is a list and can only accept integer indices. Any help?

DISCLAIMER: I am a beginner. Be gentle if I'm doing something terribly stupid :)

4

1 回答 1

0

您想使用csv.DictReader它允许您按名称访问元素。默认csv.reader将每条记录作为列表返回。

于 2013-04-10T22:42:13.020 回答