gpt4 book ai didi

python - 如何从 csv 构建嵌套有序字典?

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:44 26 4
gpt4 key购买 nike

如何获取嵌套字典,其中键和子键的顺序精确与 csv 文件中的顺序相同?

我试过了

import csv
from collections import OrderedDict

filename = "test.csv"
aDict = OrderedDict()

with open(filename, 'r') as f:
csvReader = csv.DictReader(f)
for row in csvReader:
key = row.pop("key")
aDict[key] = row

test.csv 的样子

key,number,letter
eins,1,a
zwei,2,b
drei,3,c

但子词典没有排序(行字母和数字已更改)。那么我怎样才能以有序的方式填充 aDict[key] 呢?

最佳答案

您必须根据 csv.reader 返回的行自行构建字典和子字典,这些行是序列,而不是使用 csv.DictReader

幸运的是这很容易:

import csv
from collections import OrderedDict

filename = 'test.csv'
aDict = OrderedDict()

with open(filename, 'rb') as f:
csvReader = csv.reader(f)
fields = next(csvReader)
for row in csvReader:
temp = OrderedDict(zip(fields, row))
key = temp.pop("key")
aDict[key] = temp

import json # just to create output
print(json.dumps(aDict, indent=4))

输出:

{
"eins": {
"number": "1",
"letter": "a"
},
"zwei": {
"number": "2",
"letter": "b"
},
"drei": {
"number": "3",
"letter": "c"
}
}

关于python - 如何从 csv 构建嵌套有序字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30413720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com