将csv文件转换为字典

2024-06-08 16:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我昨天问了这个问题,但我还是坚持不下来。我已经编写了一个函数,目前可以正确读取文件,但有几个问题。你知道吗

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

"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它一直在工作(但不正确),直到今天早上我做了一些修改,它现在给出了一个递归错误。你知道吗


Tags: 文件代码字典vandaleonardolinesoil
2条回答

这应该会简化您的代码一点,但我已经留下来处理标题行由您决定。你知道吗

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

你只想要这个:

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

你当前的函数正在无限地调用它自己。。。然后修复convertLines函数(如果需要)。你知道吗

相关问题 更多 >