小能豆

将 csv 文件转换为字典

py

我昨天问了这个问题,但还是想不通。我写了一个函数,目前可以正确读取文件,但有几个问题。

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

"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 它一直在运行(但不正确),直到今天早上我做了一些修改,它现在出现了递归错误。


阅读 26

收藏
2024-11-07

共1个答案

小能豆

你只想要这个:

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

你当前的函数正在无限地调用自身…convertLines如果需要的话,就修复你的函数

2024-11-07