[英]I want to create a nested dictionary from a csv file with headers as keys
[英]Create nested dictionary with same keys from a file
例如使用以下 txt 文件:
Math,Calculus,5
Math,Vector,5
Language,English,4
Language,Spanish,4
进入字典:
{
"Math": {
"Calculus": "5",
"Vector": "5"
},
"Language": {
"English": "4",
"Spanish": "4"
}
}
我已经能够编写结构,但无法解决重复键:
file = open(filename, mode='r')
dict={}
for line in file:
line=line.rstrip()
department, name, cre = line.split(';')
if department not in dict:
data = {}
dict[department] = data
data[name]=cre
else:
????
d = {}
for line in file:
line = line.rstrip()
department, name, cre = line.split(',')
if department not in d:
d[department] = {}
d[department][name] = cre
你可以这样做:
import json
with open('data.csv', mode='r') as fd:
data={}
for line in fd:
line = line.rstrip()
department, name, cre = line.split(',')
if department not in data:
data[department] = {name: cre}
else:
data[department][name] = cre
print(json.dumps(data, indent=2))
我对您的代码进行了一些更改,着眼于最佳实践:
with...
而不是仅仅打开文件(这可以确保文件被关闭)file
和dict
)冲突的变量名split
表达式以使用,
(实际分隔符)而不是;
我在这里使用json
模块只是为了打印结果; 显然你不需要那个。
运行上述产生:
{
"Math": {
"Calculus": "5",
"Vector": "5"
},
"Language": {
"English": "4",
"Spanish": "4"
}
}
关于您的代码的一些注释。
split
似乎做错了(你应该使用","
而不是";"
)
尽量不要将变量命名为类型名称(dict 是字典的类型名称)。
最后关闭文件。
这是解决方案:
file = open(filename, mode='r')
d={}
for line in file:
line=line.rstrip()
department, name, cre = line.split(',')
if department not in d:
d[department] = {}
d[department][name] = cre
file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.