Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a dictionary from a csv file in python 3

I am using Python 3.2 with a Mac OS Maverick and I am trying to get a .cvs file with this format:

'Lisa plowed ', '1A', 'field', 'field', 'field', 'field', 'field'
'John greased ', '1A', 'axle', 'wheel', 'wheels', 'wheel', 'engine'
'Tracy freed ', '1A', 'animals', 'fish', 'slaves', 'slaves', 'slaves'
'Paul alleged ', '1A', 'truth', 'crime', 'facts', 'infidelity', 'incident'

into a dictionary, with the first item in each row being the key and the remainder of the row being values mapped to that key. I have tried different things, and the closest I got was with this code, but unfortunately, I am not there yet:

   import csv

   data =open('test.csv', encoding = 'utf=8')
   reader = csv.reader(data, delimiter=",")
   for col in reader:
       print(col)
   result = {}
   for row in reader:
       key = row[0]

       result[key] = row[1:]
   print(result)

the result I got is just {} as if the dictionary was empty. I would really appreciate any help on this, either by offering a new alternative or referring me to where I can find an answer. Thanks a lot!

like image 681
user2962024 Avatar asked Dec 16 '22 04:12

user2962024


2 Answers

Try:

import csv

data={}
with open('/tmp/text.txt') as fin:
    reader=csv.reader(fin, skipinitialspace=True, quotechar="'")
    for row in reader:
        data[row[0]]=row[1:]

print(data)       
# {'Lisa plowed ': ['1A', 'field', 'field', 'field', 'field', 'field'], 'Tracy freed ': ['1A', 'animals', 'fish', 'slaves', 'slaves', 'slaves'], 'Paul alleged ': ['1A', 'truth', 'crime', 'facts', 'infidelity', 'incident'], 'John greased ': ['1A', 'axle', 'wheel', 'wheels', 'wheel', 'engine']}
like image 110
dawg Avatar answered Dec 23 '22 23:12

dawg


After the first time you iterate over reader, it is empty.

like image 40
Hyperboreus Avatar answered Dec 23 '22 22:12

Hyperboreus