0

The following code is intended to dump a long list of numbers from a csv into stat_by_symbol[symbol] so that I can call the list of numbers using each symbol as a key. For some reason, the code only seems to work for the first symbol. Can someone help me fix the code to work as intended? Many thanks.

with open('zzdata.csv', 'rb') as f:
 reader = csv.reader(f)
 reader.next()
 for symbol in symbols:#symbols in a list
 stat = []
 for row in reader:
 if symbol in row:
 stat.append(row[8])#stat becomes long list of numbers
 stat_by_symbol[symbol] = [stat]
eumiro
214k36 gold badges307 silver badges264 bronze badges
asked Dec 15, 2011 at 7:43

1 Answer 1

2

The problem is that you can iterate over reader just once (therefore just the first symbol match).

Try this:

stat_by_symbol = {}
with open('zzdata.csv', 'rb') as f:
 reader = csv.reader(f)
 reader.next()
 for row in reader:
 for symbol in symbols:#symbols in a list
 if symbol in row:
 stat_by_symbol.setdefault(symbol, []).append(row[8])
answered Dec 15, 2011 at 7:47
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I also need to iterate over row[8] through row[27] such that all the numbers in row[8] are in place 0, all the numbers from row[9] in place 1, and so on. I tried adding: for i in range(8, 28): ...append(row[i]), but this procedure doesn't separate the lists of numbers like I need. Any help on this?
@johnjdc - update your question and add a better example of what you need
Just posted a new question: stackoverflow.com/questions/8517246/…

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.