不使用库即可将CSV转换为字典

问题描述 投票:0回答:2

我有此CSV:

color,property,type,id
red,house,building,02 

我正在尝试将csv转换为具有以下结构的字典:

{
"0": {"val1": 1, "val2": 2, "val3": 3, ..., "valn": n},
"1": {"val1": 45, "val2": 7, "val3": None, ..., "valn": 68},
}

[其中val1,val2等是列的标题名称,“ 0”和“ 1”是行数。

所以我们应该有:

CSV内容是这样的:

color,property,type,id
red,house,building,02 
blue,department,flat,04

{
"0": {"color": "red", "property": "house", "type": "building", ..., "valn": n},
"1": {"color": "blue", "property": "farm", "type": "area", ..., "valn": n},
}

我如何不使用任何库就可以达到这个结果?我想从头开始实现它,而不使用CSV库等。

谢谢。

python-3.x
2个回答
0
投票

尝试这种方法:

inp = """color,property,type,id
red,house,building,02 
blue,department,flat,04
cyan,,flat,10
"""

lines = inp.split('\n')

colnames = list(map(lambda x: x.strip(), lines[0].split(',')))
lines = lines[1:]
res = {}

for i, line in enumerate(lines[:-1]):
    res[i] = {
        colname: val if val != '' else None 
        for colname, val in zip(colnames, map(lambda x: x.strip(), line.split(',')))
    }

print(res)

但是,诸如类型推断代码之类的其他功能将更加复杂:您可以按照this question的答案进行操作>


0
投票
CSV_FILE = None


def main():
    header, *lines = read_csv(CSV_FILE)
    header = header.split(",")

    result = {}
    for counter, line in enumerate(lines):
        line_dict = {}
        for idx, item in enumerate(line.split(",")):
            line_dict[header[idx]] = item
        result[str(counter)] = line_dict

    print(result)


def read_csv(filename=None):
    if filename:
        with open(filename, 'r') as file:
            return file.readlines()

    lines = """color,property,type,id
red,house,building,02 
blue,department,flat,04""".splitlines()
    return lines


if __name__ == "__main__":
    main()
© www.soinside.com 2019 - 2024. All rights reserved.