0

In the following code, row[8], row[9], ..., row[27] each contain many numbers. I need all of the numbers in row[8], row[9], etc. to append to stat_by_symbol as separate lists within within stat_by_symbol. However, the code below appends all of the numbers across all rows within a single list.

As an example of what I need, if I called stat_by_symbol['aaa'][0], then I should get the list of numbers pulled from row[8].

How can I fix this? Many thanks.

EDIT for further clarification. I've attached a snapshot of the csv. I need stat_by_symbol['aaa'][0] to give me all of the numbers under Column i. Similarly, stat_by_symbol with index 1 would give me all of the numbers under Column j.

enter image description here

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:
 for i in range(8, 28):
 stat_by_symbol.setdefault(symbol, []).append(row[i])
asked Dec 15, 2011 at 8:38
5
  • are you sure row is a list of lists? Commented Dec 15, 2011 at 8:47
  • @johnjdc - why do you keep unindenting the block after with? Commented Dec 15, 2011 at 8:51
  • @Vaughn Cato each row is a list and stat_by_symbol is supposed to collect all of those lists. Commented Dec 15, 2011 at 8:59
  • @eumiro I spaced over four times and then pasted the code. Not sure why. I fixed it, though. Commented Dec 15, 2011 at 9:02
  • @johnjdc - you said that row[8] contains many numbers, which would imply that row[8] is a list, which would imply that row is a list of lists. I think you are thinking of the variable "row" in two different ways. Commented Dec 15, 2011 at 15:34

1 Answer 1

0
stat_by_symbol = dict((symbol, [[] for i in xrange(8,28)]) for symbol in symbols)
with open('zzdata.csv', 'rb') as f:
 reader = csv.reader(f)
 reader.next()
 for row in reader:
 for symbol, symbol_list in stat_by_symbol.iteritems():
 if symbol in row:
 for symbol_list2, cell in zip(symbol_list, row[8:28]):
 symbol_list2.append(cell)
answered Dec 15, 2011 at 8:44
Sign up to request clarification or add additional context in comments.

1 Comment

I get an error when I try to run the top line: "stat_by_symbol = dict((symbol, [[] for i in xrange(8,28)]) for symbol in symbols)" I fixed the bracket, but Python also highlights for in the top line.

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.