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!
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']}
After the first time you iterate over reader
, it is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With