Problems assigning dict values to variables
I am struggling with something that must be one of those 'it is so obvious I am an idiot' problems. I have a csv file that I want to read in and use to create individual 'tables'. I have a variable (RID) that marks the beginning of a new 'table'.
I can't get my indicator variable (currentRow) to advance as I finish manipulating each line. You can see the print statements, currentRow remains equal to 0.
But if I use an assignment statement开发者_如何学JAVA outside of the loop I can change the value of currentRow at will. The test assignment is to just understand where I am getting in the loop.currentRow=0
test=0
theTables=defaultdict(list)
for line in csv.DictReader(open(r'c:\temp\testread.csv')):
newTableKey=line['CIK']+'-'+line['RDATE']+'-'+line['CDATE']+'-'+line['FNAME']+' '+line['TID']
if line['RID']=='1':
test+=1 # I can get here
if currentRow>int(line['RID']):
print 'got here'
theTables[oldTableKey]=theList
test+=1 # I cannot get here
theList=[]
theList.append(line)
currrentRow=int(line['RID'])
print currentRow #this value always prints at 0
print int(line['RID']) #this prints at the correct value
oldTableKey=newTableKey
In the line:
currrentRow=int(line['RID'])
you have three r
s in currrentRow
. Reduce them to just two, and things should improve.
One solution is to add the following somewhere inside the loop:
currentRow += 1
However, a better solution may be to use enumerable:
for currentRow, line in csv.DictReader..:
stuff
It looks to me like it's possible that theTables[oldTableKey]=theList
could be executed with an uninitialized value of oldTableKey
.
精彩评论