Reputation: 127
I've opened a file for reading and got all the lines printed out.
6,78,84,78,100
146,90,100,90,90
149,91,134,95,80
641,79,115,70,111
643,100,120,100,90
I need to grab the first number in each line to create a dictionary key. The rest of the numbers are the values for the dictionary. Is there a way to use indexing with a for loop to grab each thing from the line?
I've tried using readlines() but that has gotten overly complicated in other ways that I won't go into detail. I would prefer to keep the lines as is and iterate over them if possible.
I tried:
fo=open('tester.csv','r')
def search(fo):
for line in fo:
key=line[0]
value= (line[1],line[2],line[3],line[4])
I want my final output to be a dictionary= {6: (78,84,78,100)}
Upvotes: 1
Views: 2292
Reputation: 634
t = open("tester.csv", "r")
tstuff = t.readlines()
outdict = {}
tstufflength = len(tstuff)
for i in tstuff:
thing1, thing2 = i.split(",", 1)
realthing2 = thing2.strip("\n")
outdict[thing1]=realthing2
print(outdict)
Will only work if the lines are all on, well, different lines.
OUTPUT:
{'6': '78,84,78,100', '149': '91,134,95,80', '643': '100,120,100,90', '146': '90,100,90,90', '641': '79,115,70,111'}
Upvotes: 1
Reputation: 748
Are you trying to get an output like this?
OUTPUT:
['6', '1', '1', '6', '6']
Then,
f = open('data.csv')
result = []
for line in f:
if line != '\n':
result.append(line[0])
print(result)
Upvotes: 1