Having an csv file with 3 columns I an trying to make a dictionary. First I read the file:
fin = open('example.csv', 'r')
with these columns how I could make a dictionary?
EDITED in response to OP comment
I think what you are asking for is to turn
a,123,456
b,333,444
c,888,3434
into
{'a': ('123', '456'), 'b': ('333', '444'), 'c': ('888', '3434')}
If so, one solution is to use csv.reader to parse the file, iterate the rows and populate your final dict.
with open('example.txt', 'rb') as src_file:
csv_file = csv.reader(src_file)
data = {}
for row in csv_file:
data[row[0]] = (row[1], row[2])
print(data)
See the csv module docs at http://docs.python.org/2/library/csv.html
you can use dict_writer in csv module.
import csv
fieldnames = ['Column1', 'Column2', 'Column3']
dict_writer = csv.DictWriter(file('your.csv', 'wb'), fieldnames=fieldnames)
dict_writer.writerow(fieldnames)
dict_writer.writerows(rows)
dict from a CSV fileYou didn't say how the values should look like, so:
d={}
with open('example.csv', 'r') as file:
for line in file:
lst = line.strip().split(',')
d[lst[0]] = lst[1:]
This outputs something like:
{'key1': ['v1', 'v2'], 'key2': ['v1', 'v2']}
lst[0] is the first column in the csv file and lst[1:] is the remaining columns, and yes you can read all the lines once from file using file.readlines()with open(...) block the file is closed automatically, if you still want to access the file after that then you should use f=open(...) instead.
csvmodule instead.