[英]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.