将csv文件转换为字典

时间:2016-11-13 18:53:34

标签: python file python-3.x csv dictionary

昨天我问过这个问题,但仍然坚持下去。我编写了一个当前正确读取文件的函数,但存在一些问题。

我遇到的主要问题是我需要以某种方式跳过文件的第一行,我不确定我是否将它作为字典返回。以下是其中一个文件的示例:

"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"

我需要读取上面的文件并将其转换为如下所示的字典:

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")]
      }

这是我到目前为止所拥有的。我当前的代码有效但不会将文件转换为字典,如上例所示。谢谢你的帮助

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:
        lines.append(i)
    thefile.close()
    mydict = convertLines(read_file(filename))
    return lines

对我的代码进行一些小的更改会返回正确的结果还是我需要以不同的方式处理?看来我的当前代码读取完整文件。谢谢你的帮助

编辑:@Julien它正在工作(但不正确),直到今天早上我做了一些修改,它现在给出一个递归错误。

2 个答案:

答案 0 :(得分:0)

你只想要这个:

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

您当前的功能无限调用自己......如果需要,请修复convertLines函数。

答案 1 :(得分:0)

这应该会简化你的代码,但是我已经处理了标题行了。

from collections import defaultdict
import csv

artists = defaultdict(list)

with open('artists.csv', 'r') as csvfile:
    reader = csv.reader(csvfile,delimiter=',')
    for row in reader:
        artists[row[0]].append(row[1:-1])