0

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?

2
  • 4
    Use the csv module instead. Commented Nov 24, 2012 at 9:58
  • 1
    From your 3 columns, you will first have to decide which will be the key(s) and which will be the value(s). Commented Nov 24, 2012 at 9:59

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

If your data file is huge and memory is an issue, there are more efficient ways to do this using generators. Please comment if this is the case.
Actually, I didn't give that comment enough thought; If you want to turn the entire file into a dict (in memory) then reading it all is unavoidable. If you have duplicate keys (in column 1) then naturally some of the file will be 'ignored'. Else, it will be difficult to improve memory efficiency. How huge are your files?
It seems that reading it all into memory is unavoidable. It depends what you are trying to do with the data. Is there any way you can work with it in chunks? What is the data? What are you doing with it? It may not be a problem. Work with it and see how it performs.
1

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)

1 Comment

I think the OP is after creating a dict from a CSV file
1

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

4 Comments

@HelenFirstrofen what do you mean ?
@HelenFirstrofen 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()
I am asking this because it gives me back this error ValueError: I/O operation on closed file
@HelenFirstrofen ah I see, after the 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.
0

You can also use numpy loadtxt and create the dict.

  from numpy import loadtxt

  a,b,c = loadtxt('filename.csv', sep=',', unpack=true)
  dictionary = dict(zip(a,(b,c)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.