1

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)}

Kara
  • 6,115
  • 16
  • 50
  • 57
ocean.1234
  • 129
  • 2
  • 13

2 Answers2

1

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)
RPT
  • 728
  • 1
  • 10
  • 29
  • You cannot do that since the keys of the dictionary have to be unique. In your example the first numbers of the lines are not all unique. – RPT Apr 26 '17 at 15:04
  • `for line in f: [\ntab] dict[line[0]] = line[1:]` you can do that. But the answer would be : `{'6': '43,100,120,100,90','', '1': '49,91,134,95,80}` since the key with value '6' will be overwritten with the latest line with key '6' – RPT Apr 26 '17 at 15:06
  • Check this question: http://stackoverflow.com/questions/10664856/make-dictionary-with-duplicate-keys-in-python Could be useful. – RPT Apr 26 '17 at 15:08
  • I need them all to be integers. – ocean.1234 Apr 26 '17 at 15:33
  • @ocean.1234 : You should know this is not a place to ask people to write your code for you. We are only here to help you, not write your code. – RPT Apr 26 '17 at 15:39
  • Take a look here, http://stackoverflow.com/questions/21193682/convert-a-string-key-to-int-in-a-dictionary – RPT Apr 26 '17 at 15:39
  • In this instance my values are tuples. Not lists – ocean.1234 Apr 26 '17 at 15:53
1
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'}

E.T.
  • 614
  • 6
  • 16