user2962024
user2962024

Reputation: 317

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!

Upvotes: 4

Views: 10743

Answers (3)

dawg
dawg

Reputation: 104092

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']}

Upvotes: 8

abarnert
abarnert

Reputation: 366053

You should be able to tell from the output what's happening. First you do this:

for col in reader:
    print(col)

Since reader is an iterable of rows, this prints out every row in the CSV file. The fact that you named the variable col doesn't have any effect, except to confuse readers.

If there's a header row you want to treat specially, what you should do is this:

headers = next(reader)
for col in headers:
    print(col)

Upvotes: 1

Hyperboreus
Hyperboreus

Reputation: 32449

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

Upvotes: 3

Related Questions