I am trying to make a dictionary that will be used to save data to a csv file, and I am having trouble getting the 'fieldnames' to populate the dictionary.
I want the format to be like this:
thewriter.writerow({'time': (time[x]/100), 'current': ((adc2data[i][x]/10)-offset)})
but instead of current, it would be C1 thru C10. I am trying to do it iteratively because eventually I will want 50 or more columns, and I don't want to hard code every single one every time the number changes.
I get an error in the last for loop: "TypeError: list indices must be integers or slices, not str" but i do want them to be strings. Is there a simpler way to accomplish what I am doing? I feel like I am making things more complicated and convoluted then they need to be.
fieldnames = ['Time (us)', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10']
thewriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
thewriter.writeheader()
for i in range(len(adc2data)):
for x in range(len(adc2data[i])):
dicts = {}
keys = fieldnames
values = [None] * 11
values[0] = (time[x]/100)
for j in range(len(values)-1):
values[j+1] = ((adc2data[i][x]/10)-offset)
for v in keys:
dicts[v] = values[v]
thewriter.writerow(dicts)
I have tried changing the last for loop to:
for v in range(len(keys)):
But then the dictionary entries are of course just integer values 0-9, and the dictionary is mismatching the fieldnames list.