如何获取嵌套字典,其中键和子键的顺序精确与 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"
}
}
我是一名优秀的程序员,十分优秀!