n00bprogrammer22 n00bprogrammer22 - 1 year ago 132
Python Question

Converting csv file to dictionary python

I asked this question yesterday but am still stuck on it. I've written a function that currently reads a file correctly but there are a couple of problems.

The main problem I'm having is that I need to somehow skip the first line of the file and I'm not sure if I'm returning it as a dictionary. Here is an example of one of the files:

"Artist","Title","Year","Total Height","Total Width","Media","Country"
"Pablo Picasso","Guernica","1937","349.0","776.0","oil paint","Spain"
"Vincent van Gogh","Cafe Terrace at Night","1888","81.0","65.5","oil paint","Netherlands"
"Leonardo da Vinci","Mona Lisa","1503","76.8","53.0","oil paint","France"
"Vincent van Gogh","Self-Portrait with Bandaged Ear","1889","51.0","45.0","oil paint","USA"
"Leonardo da Vinci","Portrait of Isabella d'Este","1499","63.0","46.0","chalk","France"
"Leonardo da Vinci","The Last Supper","1495","460.0","880.0","tempera","Italy"

I need to read a file like the one above and convert it into a dictionary that looks like this:

sample_dict = {
"Pablo Picasso": [("Guernica", 1937, 349.0, 776.0, "oil paint", "Spain")],
"Leonardo da Vinci": [("Mona Lisa", 1503, 76.8, 53.0, "oil paint", "France"),
("Portrait of Isabella d'Este", 1499, 63.0, 46.0, "chalk", "France"),
("The Last Supper", 1495, 460.0, 880.0, "tempera", "Italy")],
"Vincent van Gogh": [("Cafe Terrace at Night", 1888, 81.0, 65.5, "oil paint", "Netherlands"),
("Self-Portrait with Bandaged Ear",1889, 51.0, 45.0, "oil paint", "USA")]

Here's what I have so far. My current code works but does not convert the file into a dictionary like the example above. Thanks for any help

def convertLines(lines):
head = lines[0]
del lines[0]
infoDict = {}
for line in lines:
infoDict[line.split(",")[0]] = [tuple(line.split(",")[1:])]
return infoDict

def read_file(filename):
thefile = open(filename, "r")
lines = []
for i in thefile:
mydict = convertLines(read_file(filename))
return lines

Would just a couple small changes to my code return the correct result or would I need to approach this differently? It does appear that my current code reads the full file. Thanks for any help

Edit: @Julien It was working (but not correctly) until I made some revisions this morning it is now giving a recursion error

Answer Source

You just want this:

def read_file(filename):
    with open(filename, "r") as thefile:
        mydict = convertLines(thefile.readlines()))
        return mydict

your current function is infinitely calling itself... Then fix your convertLines function if it needs to.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download